簡體   English   中英

在 Python 中修改 txt 文件行的最佳方法是什么

[英]What is the best way to modify txt file's lines in Python

例如。 我希望刪除/添加/更改 txt 文件中 24 到 40 之間的行。 我將 txt 文件導入以逐行列出。 並修改列表然后重寫一個新文件。 這是我的代碼:

def deletetfile(file):
    file = open(file)
    content = file.read()
    lines = content.splitlines()
    print(lines)
    del lines[24:40]
    print(lines)
    with open("testfile2.txt", "w") as f:
        for i in lines:

            f.write(i+'\n')

if __name__ == "__main__":
    deletetfile('testfile.txt')

但我認為它會在一個非常大的文件中運行得很慢。
有沒有更好的方法來修改 python 中的 txt 文件行?

除了潛在的性能問題,讀取 memory 中的整個文件可能會導致 memory 錯誤,因此最好在需要注釋時避免它。 在您的情況下,簡單的解決方案是逐行讀取源文件(通過迭代文件),將要保留的行復制到新文件中,然后刪除原始文件並將新文件重命名為舊文件。 另外,請注意始終關閉文件(使用with語句是這樣做的規范方法):

def delete_lines(file_path, start, end):
    tmp_path = "{}.tmp".format(file_path)
    with open(file_path) as src, open(tmp_path, "w") as dest:
        for lineno, line in enummerate(src):
            if lineno < start or lineno > end:
                dest.write(line)
    os.remove(filepath)
    os.rename(tmp_path, file_path)

if __name__ == "__main__":
    delete_lines('testfile.txt', 24, 40)

nb:未經測試的代碼,所以仔細檢查它 - 但你明白了;-)

擺脫 for 循環並將其替換為以下內容:

f.write(”\n”.join(lines))

暫無
暫無

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

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