所有其他的答案是有效的,所以你可能得到关于如何通过加载到去做一个好主意该文件,更改内容,然后将文件保存回来。
我只想指出,有可能直接在存储器中更改文件的内容。这样做并不总是明智的,这个东西有其缺点,但它对于未来的某些用途可能是有用的。
要将内容更改(删除或插入)到现有文件中,您可以使用mmap模块。
它允许您映射RAM或存储内存(文件)的一部分并访问并编辑它,就像它是一个字符串。或许一个清单最好说。
因此,要删除所需的行,请打开该文件,加载其内容并执行find()或其他操作来查找要删除的行的索引及其长度。
然后你的存储器映射文件,并简单地移动你想删除的行之后的其余内容,从而“覆盖”不需要的行。你用切片来做。然后调整内存映射的大小以切换内容后剩余的字节。因此,您将文件调整为正确的大小,然后可以关闭不会关闭文件的mmap。
您可以用这种方式在文件中插入一行。您首先调整文件大小,将内容移至最后,以便让您的线条显示出来,然后马上将其写入。
这听起来有点复杂,很多工作,但它不是真。它可以节省您每次删除该行时写入整个文件的麻烦。
我没有检查它有多快,它比每次覆盖都快。但这是我觉得值得一提的一个解决方案。
下面是一些快速组装代码:
# This needs checks and rechecks
# Also, its efficiency is questionable. Some optimization can be done with find() and rfind()
# But we can choose to believe in the module and just do it.
# The nice thing is that we can use find() to point the user, not searching for the line number like mad.
from mmap import mmap
def removeline (fname, nl):
f = open(fname, "rb+")
m = mmap(f.fileno(), 0)
size = m.size()
ixl = 0 # Index of line to delete
nle = 0 # Count new lines found
# Find the line:
while nle!=nl:
# Suppose we know our EOL will always be \n
i = m.find("\n", ixl)
if i==-1: break
ixl = i+1
nle += 1
if ixl>=size: f.close(); return # nl is greater than number of lines in the f
ixle = m.find("\n", ixl) # Index of end of that line
ixle = (ixle+1, None)[ixle==-1] #Either include the EOL in deletion or delete to the EOF
# Line length:
if ixle!=None: ll = ixle-ixl
else:
# Remove from ixl to the end of file.
# I.e. just shrink the file.
ns = size-(size-ixl)
if ns==0:
# Delete all
m.close()
f.close()
f = open(fname, "wb")
f.close()
return
m.resize(ns) # Cut off the rubbish
m.close(); f.close()
return
# Shift the rest over the offending line:
try: m[ixl:size-ll] = m[ixle:size]
except:
m.close()
f.close()
raise
ns = size-ll
if ns==0:
# Delete all - mmap doesn't like to resize to 0 bytes., hm, perhaps f.truncate()
m.close()
f.close()
f = open(fname, "wb")
f.close()
return
m.resize(ns) # Cut off the rubbish
m.close()
f.close()
你想删除的用户名或行号? – danidee
如果用户想要删除第5行和第10行删除5更改第10行是什么,或者您将不得不基本重写该文件而不删除他们想要删除的行? – depperm
@danidee用户名 –