1

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?

2
  • Did you mean: filetest.write(templine)? Commented Jun 6, 2020 at 9:39
  • i have tried doing that, but it still appends templine rather than replace line with templine Commented Jun 6, 2020 at 9:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.