簡體   English   中英

如何在Python中刪除文本文件中的行?

[英]How to erase line from text file in Python?

我正在嘗試創建一個代碼來重寫.txt文件中的特定行。 我可以寫在我想要的行,但我不能刪除行上的前一個文本。

這是我的代碼:
(我正在嘗試幾件事)

def writeline(file,n_line, text):
    f=open(file,'r+')
    count=0
    for line in f:
        count=count+1
        if count==n_line :
            f.write(line.replace(str(line),text))
            #f.write('\r'+text)

您可以使用此代碼制作測試文件以進行測試:

with open('writetest.txt','w') as f:
    f.write('1 \n2 \n3 \n4 \n5')

writeline('writetest.txt',4,'This is the fourth line')

編輯:由於某些原因,如果我使用'if count == 5:'代碼編譯好(即使它不刪除前一個文本),但如果我'如果count == n_line:',則文件結束垃圾很多。

答案工作,但我想知道我的代碼有什么問題,以及為什么我不能讀寫。 謝謝!

您正在讀取文件並寫入文件。 不要那樣做。 相反,您應該寫入NamedTemporaryFile ,然后在完成寫入並關閉它之后renamerename為原始文件。

或者,如果文件的大小保證很小,您可以使用readlines()來讀取所有文件,然后關閉文件,修改所需的行,然后將其寫回:

def editline(file,n_line,text):
    with open(file) as infile:
        lines = infile.readlines()
    lines[n_line] = text+' \n'
    with open(file, 'w') as outfile:
        outfile.writelines(lines)

使用臨時文件:

import os
import shutil


def writeline(filename, n_line, text):
    tmp_filename = filename + ".tmp"

    count = 0
    with open(tmp_filename, 'wt') as tmp:
        with open(filename, 'rt') as src:
            for line in src:
                count += 1
                if count == n_line:
                    line = line.replace(str(line), text + '\n')
                tmp.write(line)
    shutil.copy(tmp_filename, filename)
    os.remove(tmp_filename)


def create_test(fname):
    with open(fname,'w') as f:
        f.write('1 \n2 \n3 \n4 \n5')

if __name__ == "__main__":
    create_test('writetest.txt')
    writeline('writetest.txt', 4, 'This is the fourth line')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM