pythonを使用してテキストファイルから特定の行を削除する方法を教えてください。これは、あなたがメモリ内のファイル全体をロードせずにそれを行うことができます私のコードテキストファイルから特定の行を削除する方法
def Delete():
num=int(input("Enter the line number you would like to delete: "))
Del=num-1
with open("Names.txt","w")
pythonを使用してテキストファイルから特定の行を削除する方法を教えてください。これは、あなたがメモリ内のファイル全体をロードせずにそれを行うことができます私のコードテキストファイルから特定の行を削除する方法
def Delete():
num=int(input("Enter the line number you would like to delete: "))
Del=num-1
with open("Names.txt","w")
です:
with open('input.txt', 'r') as f, open('output.txt', 'w') as g:
current=0
for line in f:
if current==deleted:
break
g.write(line)
current=current+1
for line in f:
g.write(line)
あなたが最初のN行を読んで、そこからトリムするitertools.islice
を使用することができます。 islice
は、リストスライス(例えば、mylist[0:N:1]
)のように動作しますが、ファイルオブジェクトなどの任意のタイプのイテレータで動作します。
import os
import itertools
# create test file
with open('test.txt', 'w') as fp:
fp.writelines('{}\n'.format(i) for i in range(1,11))
# invent some input
del_line = int('4')
# now do the work
with open('test.txt') as infp, open('newtest.txt', 'w') as outfp:
outfp.writelines(itertools.islice(infp, 0, del_line-1, 1))
next(infp)
outfp.writelines(infp)
os.rename('newtest.txt', 'test.txt')
# see what we got
print(open('test.txt').read())
ファイル全体を反復処理して、削除する行以外のすべての行を書き込むことができます。行を数えるにはenumerate
を使用してください。
badline = int(input('which line do you want to delete?'))
with open('fordel.txt') as f, open('out.txt', 'w') as fo:
for linenum, line in enumerate(f, start=1):
if linenum != badline:
fo.write(line)
ファイルの内容を、削除する行以外の変数にコピーして、ファイルを再作成することができます。 :) –
メモ、誰かが非整数値を入力できる... – RomanPerekhrest