簡體   English   中英

使用 python 替換文本文件中的行

[英]Replace line in text file using python

這是我的程序:

filetest = open ("testingfile.txt", "r+")  
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]  
for line in filetest:
     line = line.rstrip ()
         if not ID in line:
             continue
         else:
             templine = '\t'.join(map(str, list))
             filetest.write (line.replace(line, templine)) 
filetest.close ()

我正在嘗試用 templine 替換包含在 filetest 中輸入的 ID 的整行(templine 是一個用制表符連接到字符串中的列表),我認為我的代碼的問題特別是這部分filetest.write (line.replace(line, templine)) ,因為當我運行程序時,文件中包含 ID 的行不會被替換,而是將templine添加到行尾。

例如,如果使用輸入的 ID 在 filetest 中找到的行是"Goodbye\tpython,"現在它變成了"Goodbye\tpythonHello\tTesting\tFile\t543210" ,這不是我想要的。 如何確保"Goodbye\tpython"行替換為templine "Hello\tTesting\tFile\t543210" ,而不是附加?

當您從文件中讀取時,文件指針也會移動,這可能會導致問題。 我要做的是首先讀取文件並准備好你想要的“新文件”,然后將其寫入文件中,如下面的代碼所示:

filetest = open ("testingfile.txt", "r")  
lines = filetest.readlines()
filetest.close()
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]  
for i in range(len(lines)):
    lines[i] = lines[i].rstrip()
    if ID not in lines[i]:
        continue
    else:
        templine = '\t'.join(map(str, list))
        lines[i] = templine

with open("testingfile.txt", "w") as filetest:
    for line in lines:
        filetest.write(line + "\n")

我沒有更改代碼的邏輯,但請注意,例如,如果您的文件有一個數字為“56”的行和一個數字為“5”的行,並且您輸入了 ID“5”,那么該代碼將替換這兩行。

暫無
暫無

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

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