Reputation: 105
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.
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. How do I ensure that line "Goodbye\tpython"
is replaced by templine
"Hello\tTesting\tFile\t543210"
, not appended?
Upvotes: 1
Views: 3470
Reputation: 487
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.
Upvotes: 2