0

Hi I'm trying to open simple csv file with the header from an external file:

got next file named: name.csv with next content:

Leo,Days,Ju
Tomas,Lee,Bruce
Max,Perez,Smith

If I code:

import csv
sep = ','
with open('name.csv') as csvfile:
     fieldnames = ['name', 'paterno', 'materno']
     reader = csv.DictReader(csvfile,fieldnames)
     for row in reader:
         list = (row['name'], \
                 row['materno'])
         print (sep.join(list))

The result is desired like:

Leo,Ju
Tomas,Bruce
Max,Smith

But if got an extra file with headers named hdr_name.txt with:

['name', 'paterno', 'materno']

With this new code:

import csv
sep = ','
fieldnames =  open('hdr_name.txt', 'r').read()
with open('name.csv') as csvfile:
    print(fieldnames)
    reader = csv.DictReader(csvfile,fieldnames)
    for row in reader:
        list = (row['name'], \
            row['materno'])
        print (sep.join(list))

Got as result:

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
KeyError: 'name'

But if I ask for 'name' in fieldnames, is there!

>>> 'name' in fieldnames
True
>>> 

What I'm doing wrong, with opening header from external file ?

4
  • Just read your header so fieldnames = open('hdr_name.txt', 'r').readlines() Commented Oct 4, 2017 at 21:54
  • @AndMar That unfortunately does not fix it, because the file contains a single line with a str'd list. Commented Oct 4, 2017 at 21:55
  • Yes, that's true( Commented Oct 4, 2017 at 21:57
  • More importantly, stop dumping the string representation of an object to a txt file and calling it serialization - use pre-existing serialization formats. Commented Oct 4, 2017 at 21:59

1 Answer 1

2

fieldnames is a string that looks like this:

"['name', 'paterno', 'materno']"

Naturally, a membership test will return true, but that does not imply fieldnames is a list. Remember, file.read returns a string - you still need to cast it to a list.

This doesn't appear to look like JSON, so I'd recommend ast:

import ast
with open('hdr_name.txt', 'r') as f:
     fieldnames = ast.literal_eval(f.read().strip())
Sign up to request clarification or add additional context in comments.

4 Comments

Ok. found other of the multiple ways to do it, once I got the main idea! Thanks @COLDSPEED fieldnames = eval(open('hdr_name.txt', 'r').read()) Using eval()
@IsraelDiaz try to stay away from eval, it is unsafe compared to ast.
@COLDSPEED - Oky. got it! 10xs!
Just more info about it: from documentation states: See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals. [ docs.python.org/2/library/functions.html?highlight=eval#eval ]

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.