我正在尝试从csv中读取特定的列并写入另一个csv。
这是我的代码:
import csv
with open('contribs_01.csv', 'r') as file:
csv_reader = csv.DictReader(file)
with open('01_output.csv', 'w') as new_file:
select_fields = ['contributorNameLast', 'contributorNameFirst', 'contributorStreetCity', 'contributorStreetStateCd', 'contributorStreetPostalCode', 'contributorOccupation', 'filerName']
csv_writer = csv.DictWriter(new_file, fieldnames=select_fields)
csv_writer.writeheader()
for line in csv_reader:
csv_writer.writerow(line)
运行它时,出现此错误:
Traceback (most recent call last):
File "01_donor_read.py", line 16, in <module>
csv_writer.writerow(line)
File "C:\Python27\lib\csv.py", line 152, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Python27\lib\csv.py", line 148, in _dict_to_list
+ ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: 'contributorParent1LawFirmName', 'receivedDt', 'recordType', 'contributionAmount', 'contributorNamePrefixCd', 'contributorPacFein', 'contributorStreetCountyCd', 'contributorParent2LawFirmName', 'schedFormTypeCd', 'contributionDescr', 'contributorEmployer', 'contributorStreetRegion', 'contributionDt', 'contributorStreetCountryCd', 'contributorSpouseLawFirmName', 'contributorNameShort', 'formTypeCd', 'infoOnlyFlag', 'filerTypeCd', 'contributorOosPacFlag', 'contributorJobTitle', 'itemizeFlag', 'contributorNameOrganization', 'contributorNameSuffixCd', 'travelFlag', 'filerIdent', 'reportInfoIdent', 'contributionInfoId'
有人有什么想法吗?