On 09/05/2015 23:46, Vincent Davis wrote:
I am reading a file with Dictreader and writing a new file. I want use the
fieldnames in the Dictwriter from the reader. See below How should I be
doing this?

See how I am using reader.fieldnames in the the Dictwriter. I get an error
(below)

with open(readfile, 'r', encoding='utf-8', errors='ignore', newline='') as
csvread:
     reader = DictReader(csvread)
     with open(writefile, 'w') as csvwrite:
         writer = DictWriter(csvwrite, delimiter=',',
fieldnames=reader.fieldnames)
         for line in reader:
             pass

ValueError                                Traceback (most recent call
last)<ipython-input-13-0dac622bb8a9> in <module>()----> 1
reader.fieldnames()
/Users/vmd/anaconda/envs/py34/lib/python3.4/csv.py in fieldnames(self)
     94         if self._fieldnames is None:     95
try:---> 96                 self._fieldnames = next(self.reader)
97             except StopIteration:     98                 pass
ValueError: I/O operation on closed file.

Thanks
Vincent
​ Davis​


From https://docs.python.org/3/library/csv.html#module-csv

"class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds) Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. The fieldnames parameter is a sequence whose elements are associated with the fields of the input data in order. These elements become the keys of the resulting dictionary. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. If the row read has more fields than the fieldnames sequence, the remaining data is added as a sequence keyed by the value of restkey. If the row read has fewer fields than the fieldnames sequence, the remaining keys take the value of the optional restval parameter. Any other optional or keyword arguments are passed to the underlying reader instance."

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to