Python 通过从现有的 csv 文件中过滤选定的行来编写一个新的 csv 文件 [英] Python write a new csv file by filtering selected rows from an existing csv file
问题描述
只是一个问题,我试图将 .csv 文件中的选定行写入新的 .csv 文件,但出现错误.
just a question, I was trying to write selected rows from a .csv file to a new .csv file, but there is an error.
我试图读取的 test.csv 文件是这样的(两列):
The test.csv file that I was trying to read is like this(two columns):
2013-9 1
2013-10 2
2013-11 3
2013-12 4
2014-1 5
2014-2 6
2014-3 7
2014-4 8
2014-5 9
由于我只想要 2014 年,这是我的代码:
Since I only want year 2014, here is my code:
import re
import csv
write_flag=0
string_storage=[]
rad_file=open('year.csv')
for rad_line in rad_file:
if write_flag==1:
string_storage.append(rad_line)
if (rad_line.has_key('2014')):
write_flag=1
if (rad_line.has_key('2013')):
write_flag=0
rad_file.close()
out_file = open("try.csv","w")
for temp_string in string_storage:
out_file.write(temp_string)
out_file.close()
然而,错误是:AttributeError: 'str' 对象没有属性 'has_key'
however, the error is: AttributeError: 'str' object has no attribute 'has_key'
不知道正确的编程方法,请帮助我谁是新的python用户谢谢
Have no idea of the correct way to program this, please help me who is a new python user Thanks
推荐答案
既然你在使用 csv 模块,为什么不在读取文件时写入文件:
Since you are using the csv module anyway, why not write the file as you are reading it in:
import csv
with open('in.csv', 'r') as i, open('out.csv', 'w') as o:
r = csv.reader(i, delimiter='\t')
w = csv.writer(o, delimiter='\t')
for row in r:
if row[0].split('-')[0] == '2014':
w.write(row)
这篇关于Python 通过从现有的 csv 文件中过滤选定的行来编写一个新的 csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!