[英]Read lines from file and subsequently only write those lines to the file which don't contain a certain phrase
I have one column list file: 我有一个列列表文件:
$ cat test
blah
blahblah
blah22
bluh
blih
blihihih
All I want to is to remove blah
-like lines. 我想要是删除
blah
般的线条。 (Equivalent of bash grep -v blah
.) So that blah
, blahblah
and blah22
are removed. (相当于bash
grep -v blah
。)所以blah
, blahblah
和blah22
被删除了。
I have this so far: 到目前为止我有这个:
>>> f = open('test', 'rw+')
>>> line = f.readlines()
>>> for l in line:
... if l.find('blah') == -1:
... f.truncate(0)
... f.write(l)
...
>>> f.close()
I thought it would be fine, but after running this, from test file only this line is left: 我认为这样会很好,但在运行之后,从测试文件中只剩下这一行:
$cat test
blihihih
How come, this has removed blih
or bluh
? 怎么来,这已经取消了
blih
或bluh
?
How come, this has removed
blih
orbluh
?怎么来,这已经取消了
blih
或bluh
?
To answer your question, you truncate the file too often. 要回答您的问题,请经常截断文件。 Every call to
f.truncate(0)
will reset the file size to 0. Therefore only the last line blihihih
will survive. 每次调用
f.truncate(0)
都会将文件大小重置为0.因此只有最后一行blihihih
才能生存。
If you want to do it in one go: 如果你想一次性完成:
f = open('test.txt', 'r+')
lines = f.readlines()
f.seek(0)
for line in lines:
if line.find('blah') < 0:
f.write(line)
f.truncate()
f.close()
Additionally, you should really use with
: 此外,你应该使用
with
:
with open('test.txt', 'r+') as f:
lines = f.readlines()
f.seek(0)
for line in lines:
if line.find('blah') < 0:
f.write(line)
f.truncate()
(You won't need to write f.close()
then. Read more about why using with
here for example.) (你不需要写
f.close()
然后。阅读更多关于为什么with
这里使用的例子。)
I think is best if you open the file first, and then write to it: 我认为最好先打开文件,然后写入:
# open file
lines = open('test').readlines()
# over-write the file
with open('test', 'w') as out:
for line in lines:
if 'blah' not in line:
out.write(line)
Output (in test) 输出 (测试中)
bluh
blih
blihihih
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.