0

Not able to replace the string in file

with open("dc_setup.tcl",'r+') as file:
        for line in file:
         if str0 in line:
            line1=line
            print(line1)
            contents=file.read()
            contents=contents.replace(line1,new_str)
            file.seek(0)
            file.truncate()
            file.write(contents)   

I expect the code to replace string in that file , but I'm getting empty file

3
  • 1
    First, it is not known what is new_str. Second, if new_str is a valid string, you can check the contents by print(contents) first before & after the replacement. Commented Apr 29, 2019 at 9:49
  • print(contents) does not print anything before and after replacement . And , new_str is a valid string Commented Apr 29, 2019 at 10:17
  • If contents are not printed before replacement, then your file could be empty. Check the file contents and isolate the problem by reading the file separately and viewing the contents. Commented Apr 29, 2019 at 10:23

1 Answer 1

1

This section:

file.seek(0)
file.truncate()
file.write(contents)

Is overwriting the entire file, not just your current line. Editing text files in place is generally pretty hard, so the usual approach is to write to a new file. You can copy the new file back over the old file once you've finished if you like.

with open("dc_setup.tcl") as infile, open("new_dc_setup.tcl", "w") as outfile:
    for line in infile:
        if old_str in line:
            line = line.replace(old_str, new_str)
        outfile.write(line)
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.