在python中连接两列
你好 我想连接csv文件中的两列,并将此字符串放入另一个csv文件中,但放入一列 我尝试过的代码:在python中连接两列,python,csv,Python,Csv,你好 我想连接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 r
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()
我的问题是,结果
不是在输出文件的单个列中写入的,而是在单独的列中写入每个字符
请注意,print()
这方面有什么帮助吗?
提前谢谢你 试试这个:
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()
为了进一步说明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)