def remove_line(fname, line):
'''Remove line from file by creating a temporary file containing all lines
from original file except those matching the given line, then copying the
temporary file back into the original file, overwriting its contents.
'''
with lockfile.FileLock(fname):
tmp = tempfile.TemporaryFile()
fp = open(fname, 'rw+')
# write all lines from orig file, except if matches given line
for l in fp:
if l.strip() != line:
tmp.write(l)
# reset file pointers so entire files are copied
fp.seek(0)
tmp.seek(0)
# copy tmp into fp, then truncate to remove trailing line(s)
shutil.copyfileobj(tmp, fp)
fp.truncate()
fp.close()
tmp.close()
corpus.py 文件源码
python
阅读 37
收藏 0
点赞 0
评论 0
评论列表
文章目录