[英]When I export data to a csv from Python, the file is blank. When I use Print function to see the data, the first string is returned
I am very new to python. 我是python的新手。 I am looking to import data from a .csv into python, use the fields as a variable so that I can string together the inbound data with machine language codes and then export the completed string to a .txt file. 我希望将数据从.csv导入python,将字段用作变量,以便我可以将输入的数据与机器语言代码串在一起,然后将完整的字符串导出到.txt文件。
I have the import.csv code working and have defined my variables into python and when I print the results I can see the first line as I need it to output to the .txt file. 我有import.csv代码,并且已将变量定义为python,当我打印结果时,可以看到第一行,因为我需要将其输出到.txt文件。 The issue that I am having is that in trying multiple different write statements, my file is either blank or I get errors. 我遇到的问题是,在尝试多个不同的写语句时,我的文件为空或出现错误。
import csv
with open('july 19.csv',mode='r') as csv_file:
reader = csv.DictReader(csv_file)
for records in reader:
EIN = records['EIN']
DATE = records['Date Established']
DUNS = records['DUNS #']
COMPANYNAME = records['Company Name']
lineout =('<S>'+ EIN+'$EIN '+EIN+'*'+DATE+')'+COMPANYNAME+'#D-U-N-S '+DUNS)
with open('test2.csv','w') as csvfile:
fieldnames = ['EIN','Date Established','DUNS #','Company Name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerows({'EIN' : lineout})
File "C:/Users/sstibal/PycharmProjects/Training/venv/Training.py", line 14, in <module>
writer.writerows({'EIN' : lineout})
File "C:\Users\sstibal\AppData\Local\Programs\Python\Python37-32\lib\csv.py", line 158, in writerows
return self.writer.writerows(map(self._dict_to_list, rowdicts))
File "C:\Users\sstibal\AppData\Local\Programs\Python\Python37-32\lib\csv.py", line 148, in _dict_to_list
wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'str' object has no attribute 'keys'
You're missing the fieldnames parameter on writer = csv.DictWriter(f, fieldnames)
您在writer = csv.DictWriter(f, fieldnames)
上缺少fieldnames参数
The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file f. fieldnames参数是键序列,用于标识字典中传递给writerow()方法的值写入文件f的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.