[英]Searching a csv file for elements on a list Python
I need some help with a script I made in Python and it's not working. 我需要一些使用Python编写的脚本的帮助,但该脚本无法正常工作。
So I have a file with some identifiers (numbers), that I turn into a list. 所以我有一个带有一些标识符(数字)的文件,我将其变成一个列表。 so far so good!
到现在为止还挺好!
Then I want to check a .csv file, and if the first element of the line is on the previous list write that line to a new .csv file. 然后,我想检查一个.csv文件,如果该行的第一个元素在上一个列表中,则将该行写入新的.csv文件。
My script looks like this: 我的脚本如下所示:
tratamento = open('therapies.csv')
tratados_B = open('tratados_SubB.csv')
Outfile = open('subtype_B_Tratamento.csv', 'w')
treated_list = []
for line in tratados_B:
TL = line.strip()
treated_list.append(TL)
for line in tratamento:
TLB = line.strip().split(';')[0]
if TLB in treated_list:
Outfile.write(line)
else:
pass
Any idea of what am I doing wrong? 知道我在做什么错吗?
Thank you in advance! 先感谢您!
Try to add Outfile.close()
at the end of your script. 尝试在脚本末尾添加
Outfile.close()
。
A better way of doing this is to use the with
keyword. 更好的方法是使用
with
关键字。
treated_list = []
with open('subtype_B_Tratamento.csv', 'w') as Outfile,
open('therapies.csv') as tratamento,
open('tratados_SubB.csv') as tratados_B:
for line in tratados_B:
TL = line.strip()
treated_list.append(TL)
for line in tratamento:
TLB = line.strip().split(';')[0]
if TLB in treated_list:
Outfile.write(line)
With
handles the closing of the file for you. With
为您处理文件的关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.