- Problem: trying to write header row in csv file.
- ###### read json file ######################
- with open('test.json', 'r') as j:
- reader = json.load(j)
- for row in reader:
- print(row)
- print(type(reader[0]))
- print(list(reader[0].keys()))
- ######### write json back to csv file ###################
- with open('test2.csv', 'w', encoding='utf-8', newline='') as fcsv:
- fnames = list(reader[0].keys())
- writer = csv.DictWriter(fcsv, fieldnames=fnames, )
- writer.writerow(fnames) #--- this is what caused the error
- for row in reader:
- print(type(row))
- writer.writerow(row)
- >>>
- ---------------------------------------------------------------------------
- AttributeError Traceback (most recent call last)
- c:\test\testjson.ipynb Cell 1 in <module>
- 29 fnames = list(reader[0].keys())
- 30 writer = csv.DictWriter(fcsv, fieldnames=fnames, )
- ---> 31 writer.writerow(fnames)
- 32 for row in reader:
- 33 print(type(row))
- File c:\Python3\lib\csv.py:154, in DictWriter.writerow(self, rowdict)
- 153 def writerow(self, rowdict):
- --> 154 return self.writer.writerow(self._dict_to_list(rowdict))
- File c:\Python3\lib\csv.py:147, in DictWriter._dict_to_list(self, rowdict)
- 145 def _dict_to_list(self, rowdict):
- 146 if self.extrasaction == "raise":
- --> 147 wrong_fields = rowdict.keys() - self.fieldnames
- 148 if wrong_fields:
- 149 raise ValueError("dict contains fields not in fieldnames: "
- 150 + ", ".join([repr(x) for x in wrong_fields]))
- AttributeError: 'list' object has no attribute 'keys'
- Test solution: use writer.writeheader() to add the header row - hard coded list of field names for testing
- ######### write json back to csv file ###################
- with open('test2.csv', 'w', encoding='utf-8', newline='') as fcsv:
- fnames = ['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked']
- writer = csv.DictWriter(fcsv, fieldnames=fnames, )
- writer.writeheader()
- for row in reader:
- #print(type(row))
- writer.writerow(row)
- Final solution: without hard-coding the field names. Get them directly from the Json reader list object.
- ######### write json back to csv file ###################
- with open('test3.csv', 'w', encoding='utf-8', newline='') as fcsv:
- fnames = list(reader[0].keys())
- writer = csv.DictWriter(fcsv, fieldnames=fnames, )
- writer.writeheader()
- for row in reader:
- #print(type(row))
- writer.writerow(row)
- ------
- test.csv contents:
- PassengerId,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
- 892,3,"Kelly, Mr. James",male,34.5,0,0,330911,7.8292,,Q
- 893,3,"Wilkes, Mrs. James (Ellen Needs)",female,47,1,0,363272,7,,S
- 894,2,"Myles, Mr. Thomas Francis",male,62,0,0,240276,9.6875,,Q
- 895,3,"Wirz, Mr. Albert",male,27,0,0,315154,8.6625,,S
- Related video:
- Writing CSV Files with csv.writer and DictWriter
- https://www.youtube.com/watch?v=jnkPnNaLY3g
Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.
Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license