使用Python在特定列中搜索特定值
我有一个文本文件,里面的数据是用制表符分隔的,我想在这个文件的特定列中查找一个值。
我觉得我需要用到csv导入功能,但到现在为止都没有成功。有人能给我指个方向吗?
谢谢!
**更新**
感谢大家的更新。我知道我可能可以用awk来处理这个问题,但为了练习,我想用python来完成。
现在我遇到了以下错误:
if row.split(' ')[int(searchcolumn)] == searchquery:
IndexError: list index out of range
这是我代码的一部分:
#open the directory and find all the files
for subdir, dirs, files in os.walk(rootdir):
for file in files:
f=open(file, 'r')
lines=f.readlines()
for line in lines:
#the first 4 lines of the file are crap, skip them
if linescounter > startfromline:
with open(file) as infile:
for row in infile:
if row.split(' ')[int(searchcolumn)] == searchquery:
rfile = open(resultsfile, 'a')
rfile.writelines(line)
rfile.write("\r\n")
print "Writing line -> " + line
resultscounter += 1
linescounter += 1
f.close()
我从用户那里获取了searchcolumn和searchquery的输入。我猜我现在出现“列表索引超出范围”的原因是因为文件没有正确解析?
再次感谢。
3 个回答
0
这段代码会打印出文件 filename
中所有在第四列(用制表符分隔)包含 'myvalue' 的行:
with open(filename) as infile:
for row in infile:
if row.split('\t')[3] == 'myvalue':
print row
你可以根据需要替换数字 3、'myvalue' 和 print
。
1
是的,你需要使用csv模块,并且要把分隔符设置为'\t',也就是制表符:
spamReader = csv.reader(open('spam.csv', 'rb'), delimiter='\t')
之后你就可以进行遍历了:
for row in spamReader:
print row[n]
3
你也可以使用嗅探器(这个例子来自于 http://docs.python.org/library/csv.html)
csvfile = open("example.csv", "rb")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)