只是一个问题,我试图将选定的行从一个.csv文件写入一个新的.csv文件,但是有一个错误。
我试图读取的test.csv文件如下(两列):
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年,下面是我的代码:
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’
不知道正确的编程方法,请帮助我谁是一个新的python用户谢谢
发布于 2014-09-05 14:05:35
既然您正在使用csv模块,那么为什么不在读取文件时写入它呢?
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)发布于 2014-09-05 13:51:07
通过将has_key改为startswith可以“修复”错误,但更重要的是,根据程序当前的编写方式,您将跳过从2014年开始的第一行,并包括从2013年开始的后续组的第一行。这就是你想要的吗?
如果您只是想保留从2014年开始的所有行,那么:
with open('year.csv') as rad_file, open("try.csv","w") as out_file:
header = next(rad_file)
out_file.write(header)
for rad_line in rad_file:
if rad_line.startswith('2014'):
out_file.write(rad_line)通过在读取每一行时处理它们,可以避免在列表string_storage中积累行,从而节省内存。在处理大型文件时,这一点可能很重要。
另外,如果使用with-statement打开文件,那么当执行流离开with-语句时,文件将自动关闭。
注意,在Python2中,dicts有一个has_key方法来检查dict是否有特定的键。
代码引发错误,因为rad_line是字符串,而不是dict。
has_key方法在Python3中被删除。在Python2的现代版本(如Python2.7 )中,您不需要使用has_key,因为key in dict比dict.has_key(key)更好。
发布于 2014-09-05 13:47:47
使用string.find或正则表达式查找字符串中的子字符串。
所以而不是
if (rad_line.has_key('2014')):你可以:
if (rad_line.find('2014') <> -1):https://stackoverflow.com/questions/25687348
复制相似问题