我想将 Python 元组转换为 .csv
文件。假设我有一个 retrive() 函数,当我用 pprint
打印它时,它看起来像这样:
test = tuple(retrive(directory))
pprint(test, width=1)
然后:
("opinion_1.txt, I am an amateur photographer and own three DSLR c.... purchase",
"opinion_2.txt, This my second Sony Digital Came.... good camera for a good price!',
'opinion_3.txt, \'I ordered this camera with high hopes after couldn\\\'t find.\'')
因此,我尝试使用 csv
模块:
with open('/Users/user/Downloads/output.csv','w') as out:
csv_out=csv.writer(out)
csv_out.writerow(['id','content'])
for row in test:
csv_out.writerow(row)
问题是我得到了一个奇怪的输出,看起来像这样:
id,content
o,p,i,n,i,o,n,_,1,.,t,x,t,",", ,I, ,a,m, ,a,n, ,a,m,a,t,e,u,r, ,p,h,o,t,o,g,r,a,p,h,e,r, ,a,n,d, ,o,w,n, ,t,h,r,e,e, ,D,S,L,R, ,c,a,m,e,r,a,s, ,w,i,t,h, ,a, ,s,e,l,e,c,t,i,o,n, ,o,f, ,l,e,n,s,e,s,., ,H,o,w,e,v,e,r, ,t,h,a,t, ,c,o,l,l,e,c,t,i,o,n,
我怎样才能得到这样的东西:
opinion_1.txt,I am an amateur photographer and own three DSLR c.... purchase
opinion_2.txt,This my second Sony Digital Came.... good camera for a good price!
opinion_3.txt,I ordered this camera with high hopes after couldn\\\'t find.
最佳答案
CSV 尝试迭代您从元组传递的字符串。将您的代码更改为:
for row in test:
csv_out.writerow(row.split(', ', 1))
这意味着您通过 ', '
的第一次出现来拆分元组中的每个字符串。
它为每一行生成两个元素,这就是 csv 编写器所需要的。
关于python - 如何将 Python 元组转换为 .csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35837121/