所有其他的答案是有效的,所以你可能得到關於如何通過加載到去做一個好主意該文件,更改內容,然後將文件保存回來。
我只想指出,有可能直接在存儲器中更改文件的內容。這樣做並不總是明智的,這個東西有其缺點,但它對於未來的某些用途可能是有用的。
要將內容更改(刪除或插入)到現有文件中,您可以使用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用戶名 –