我尝试使用某些条件从文件中删除行,但是当我运行脚本时,它只删除整个文件。当我将脚本更改为“只读”'它返回带有搜索条件的行但是当我在'中写入'模式它并从打印每一行改变它以删除每一行它清空整个事物。
#!/usr/bin/env python
f = raw_input('Enter filename > ')
with open(f, 'w+') as fobj:
criteria = raw_input('Enter criteria > ')
for eachLine in fobj:
if criteria in eachLine:
fobj.remove(eachLine)
break
fobj.close()
答案 0 :(得分:0)
我希望您想删除具有特定条件的行。您只需创建另一个文件,然后在该文件中写入内容,如下所示:
<div class="tags">
@foreach ($tags as $tag)
<span class="label label-default">{{ $tag }}</span>
@endforeach
</div>
答案 1 :(得分:0)
来自文档:
w+ Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated. The stream is positioned at
the beginning of the file.
a+ Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.
所以你在截断包含with open
的行上的文件。您可能想要创建一个具有不同名称的新文件,并在程序结束时将其重命名。