简体   繁体   English

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

[英]Replace line in text file using python

This is my program:这是我的程序:

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 ()

I'm trying to replace an entire line containing the ID entered in filetest with templine (templine was a list joined into a string with tabs), and I think the problem with my code is specifically this part filetest.write (line.replace(line, templine)) , because when I run the program, the line in the file containing ID doesn't get replaced, but rather templine is added to the end of the line.我正在尝试用 templine 替换包含在 filetest 中输入的 ID 的整行(templine 是一个用制表符连接到字符串中的列表),我认为我的代码的问题特别是这部分filetest.write (line.replace(line, templine)) ,因为当我运行程序时,文件中包含 ID 的行不会被替换,而是将templine添加到行尾。

For example, if the line in filetest found using the ID entered was "Goodbye\tpython," now it becomes "Goodbye\tpythonHello\tTesting\tFile\t543210" which is not what I want.例如,如果使用输入的 ID 在 filetest 中找到的行是"Goodbye\tpython,"现在它变成了"Goodbye\tpythonHello\tTesting\tFile\t543210" ,这不是我想要的。 How do I ensure that line "Goodbye\tpython" is replaced by templine "Hello\tTesting\tFile\t543210" , not appended?如何确保"Goodbye\tpython"行替换为templine "Hello\tTesting\tFile\t543210" ,而不是附加?

As you are reading from the file the file pointer moves as well and it can cause problems.当您从文件中读取时,文件指针也会移动,这可能会导致问题。 What I would do is first read the file and prepare the "new file" that you want, and then write it into the file, as shown in the code below:我要做的是首先读取文件并准备好你想要的“新文件”,然后将其写入文件中,如下面的代码所示:

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")

I didn't change the logic of the code but be aware that if your file has, for example, a line with the number "56" and a line with the number "5", and you enter the ID "5", then the code will replace both of those lines.我没有更改代码的逻辑,但请注意,例如,如果您的文件有一个数字为“56”的行和一个数字为“5”的行,并且您输入了 ID“5”,那么该代码将替换这两行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM