[英]How to print the lines of a text file that contain a certain string in Python?
[英]Remove lines from a text file which do not contain a certain string with python
我正在尝试在日志文件中形成特定用户名的报价文件。 如何删除其中不包含特定用户名的每一行? 或如何将包含该用户名的所有行写入新文件?
with open('input.txt', 'r') as rfp:
with open('output.txt', 'w') as wfp:
for line in rfp:
if ilikethis(line):
wfp.write(line)
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)
我有点像第一个更好,但是对于大文件,它可能会拖累。
遵循以下原则即可:
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
我知道您要使用python,但是如果您使用的是unix,这是grep的工作。
grep name file
如果您不在Unix上,那么...上面的答案可以解决问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.