美好的一天,
我想从csv文件中连接两个列,并将此字符串放入另一个csv文件,但是放入一个列。
我尝试过的代码:
import csv
file1=open('Source.csv','r')
readfile=csv.reader(file1,delimiter=';')
file2=open('Output.csv','w',newline='')
result=()
for row in readfile:
if (row[2]>condition1 and 'string' in row[6]):
result=str(row[2])+'- '+str(row[6])
print(result)#line just to see to info from the output file
writefile=csv.writer(file2,delimiter=';')
writefile.writerow(result)
file1.close()
file2.close()
我的问题是result
没有写在输出文件的单个列中,但每个字符都写在一个单独的列中。
请注意,print()
似乎是我想要放在输出文件中的。
这样有些帮助吗? 提前谢谢!
答案 0 :(得分:1)
为了扩展Rahul的答案,我强烈建议使用ContextManager(with
)。即使在处理它们时发生异常,它也可以确保您的文件有效关闭。
像这样:
import csv
with open('Source.csv') as file1:
readfile = csv.reader(file1,delimiter=';')
with open('Output.csv','w',newline='') as file2:
writefile = csv.writer(file2,delimiter=';')
for row in readfile:
if row[2] > condition1 and 'string' in row[6]:
result = [str(row[2]) + '- ' + str(row[6])]
print(result)#line just to see to info from the output file
writefile.writerow(result)
答案 1 :(得分:0)
试试这个:
import csv
file1=open('Source.csv','r')
readfile=csv.reader(file1,delimiter=';')
file2=open('Output.csv','w',newline='')
writefile=csv.writer(file2,delimiter=';')
result=()
for row in readfile:
if (row[2]>condition1 and 'string' in row[6]):
result=[str(row[2])+'- '+str(row[6])]
print(result)#line just to see to info from the output file
writefile.writerow(result)
file1.close()
file2.close()