0

I am writing and testing a function for opening a .csv file and save information in a dictionary, instead of using import csv.

The csv file is like:

16SAP,12/02/24,sapin-9,MATEYIJDNS
FAS1,01/02/21,fasiculata,MTYEUSOLD
EDS5,10/20/20,epsilon,MHGSJDKDLSKDKDJS
etc....

and .csv file has a (,) separated format and 4 fields: identifier, date, name and sequence, respectively.

My code is:

def dicfromcsv(csv_file):
    with open('csv_file', 'r') as f:
        d = {}
        l = f.read().split(',')
        for i in l:
            values = i.split(':')
            d[values[0]] = values[1], values[2], values[3], values[4]

dicfromcsv('PDB.csv')

But it doesn't function.

Thank in advance

5
  • can you use the panda's library instead? this may help you w3schools.com/python/pandas/pandas_csv.asp Commented Feb 24, 2022 at 21:59
  • 1
    There's no : in your file, what is i.split(':') supposed to do? Commented Feb 24, 2022 at 22:00
  • Perhaps Python's csv module? docs.python.org/3/library/csv.html Commented Feb 24, 2022 at 22:00
  • You're not processing the file line by line. l is not a line, it's one of the comma-separator fields in the file. Commented Feb 24, 2022 at 22:01
  • with open('csv_file' is going to try to open a file literally named "csv_file" Commented Feb 24, 2022 at 22:02

1 Answer 1

1
  1. Don't quote csv_file, you want to use the value of the variable.
  2. Use the csv module to parse the file.
  3. Loop over the records in the file, rather than splitting the entire file at , characters.
  4. You can use a list slice to get all the fields of the record after the first field.
  5. Your file only has 4 fields, there's no values[4]
import csv

def dicfromcsv(csv_file):
    d = {}
    with open(csv_file, 'r') as f:
        csvf = csv.reader(f)
        for values in csvf:
            d[values[0]] = tuple(values[1:])
    return d
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.