用Python从文本文件中删除不包含特定字符串的行
我想从一个日志文件中提取某个特定用户名的引用记录。请问我该怎么做才能删除掉所有不包含这个用户名的行呢?或者,我该如何把所有包含这个用户名的行写入一个新文件呢?
4 个回答
2
类似下面的代码就可以了:
newfile = open(newfilename, 'w')
for line in file(filename, 'r'):
if name in line:
newfile.write(line)
newfile.close()
你可以查看这个链接了解更多信息: http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects
f.readlines() 这个方法会返回一个列表,里面包含了文件中的所有行。
还有一种读取文件行的方式,就是直接循环遍历文件对象。这种方法更节省内存,速度也快,代码也更简单。
>>> for line in f:
print line
你还可以看看 with
这个关键字的用法。它的好处是,当代码块执行完后,文件会被正确关闭。
>>> with open(filename, 'r') as f:
... read_data = f.read()
>>> f.closed
True
3
with open(logfile) as f_in:
lines = [l for l in f_in if username in l]
with open(outfile, 'w') as f_out:
f_out.writelines(lines)
或者如果你不想把所有的行都存储在内存里
with open(logfile) as f_in:
lines = (l for l in f_in if username in l)
with open(outfile, 'w') as f_out:
f_out.writelines(lines)
我个人更喜欢第一个方法,但如果文件很大,可能会比较慢。
3
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言进行解释。