0

I want to edit a a big file in specific lines. So it isnt a good Idea to read the whole file before editing, thats why I dont want to use:

myfile.readlines()

I have to read each line check if there a special content in it and then i have to edit this line.

So far Im reading every line:

file = open("file.txt","r+")
i = 0
for line in file:
    if line ......:
        //edit this line
        //this is where i need help


file.close()

So the Question is: How can I edit the current line in the If Statement for example: if the current line is "test" I want to replace it with "test2" and then write "test2" back into the file into the line where "test" was before

Loois95
  • 85
  • 12

2 Answers2

2

This will help

import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')
Rahul Agarwal
  • 4,034
  • 7
  • 27
  • 51
0

ok so as @EzzatA mentioned in the comments below the question it seems to be the best way to read the original file and create a new one with the edited data. So something like this:

original_file = open("example.txt","r")
new_file = open("example_converted.xml","w")

string_tobe_replace = "test"
replacement_string = "test2"

for line in original_file:
    if string_tobe_replace in line:
        new_line = line.replace(string_tobe_replace,replacement_string)
        new_file.write(new_line)
    else:
        new_file.write(line)



original_file.close()
new_file.close()
Loois95
  • 85
  • 12