他のすべての答えが有効ですファイルを保存し、内容を変更してファイルを保存し直します。
ファイルの内容をストレージメモリに直接変更する可能性があることを指摘したいだけです。そうすることは常に賢明ではないが、問題には欠点があるが、それは将来のある用途では有用かもしれないからである。
コンテンツを既存のファイルに変更(削除または挿入)するには、mmapモジュールを使用します。
RAMやストレージのメモリ(ファイル)の一部をマップし、文字列のようにアクセスして編集することができます。たぶんそれは言いたいことでしょう。
ファイルを開くには、ファイルを開き、その内容を読み込んでfind()などを実行して、削除する行のインデックスとその長さを探します。
ファイルをメモリマップし、削除したい行の次の部分を上に移動するだけで不要な行を「カバー」するだけです。あなたはスライスを使ってそれを行います。次に、コンテンツを移動した後、残りのバイトを切り捨てるようにメモリマップのサイズを変更します。したがって、ファイルのサイズを正しいサイズに変更してから、ファイルを閉じないmmapを閉じることができます。
このようにしてファイルに行を挿入することができます。最初にファイルのサイズを変更し、最後にコンテンツをシフトして、行を表示するスペースを作り、それを書き込んでください。
少し複雑で作業は多いようですが、そうではありません本当に。これは、行を削除するたびにファイル全体を書き込む手間を省きます。
私はそれがどれほど速いかを確認しておらず、毎回上書きするよりも速いです。しかし、これは私が言及する価値があると感じた1つの解決策です。ここで
は、いくつかの迅速組み立てコードです:
# 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行目を削除する5行目を変更するか、削除したい行なしにファイルを書き直す必要がありますか? – depperm
@danidee username –