Hello.Please i have a problem with my code.I am trying to edit a file.The problem occurs when i use the seek function.for example,i have a file outlined like this:

myfile.txt

<Name>Ben</Name>
<Age>32</Age>
<Sex>Male</Sex>
<Country>Mars City</Country>

Now,when i try to edit the Age,i use the code:

f=open('myfile.txt','a')
f.seek(17,0)
f.write('<Age>1200</Age>')
f.close()

This code edits the Age but it ends up chopping off parts of the line
below it.Something like this:

myfile.txt

<Name>Ben</Name>
<Age>32</Age>Sex>Male</Sex>
<Country>Mars City</Country>

Please how do i edit the content of a file effectively.Is it a good idea to load the contents in a variable and manipulate it,what if i have over a billion bytes in the file?

Also,how do i delete from a file?

Thanks in advance

The extra two characters that you are adding (ie 32 -> 1200) are over writing the '\n' and the '<', which is why editing a file with seek is a terrible idea unless you're simply replacing character for character.

A better idea would be to load the file into memory, edit to your heart's content, and then re-write the file.

My suggestion is to read the file in line by line and write it out to a new file line by line in one loop. Then you can process the line in question and write it out as it comes along. This way you don't have a memory problem with very large files.

Something like this:

file_in = open("myfile.txt", "r")
file_out = open("myfile_modified.txt", "w")

search = "<Age>32</Age>"
my_line = "<Age>1200</Age>"

print("working ...")

for line in file_in:
    # strip of the trailing '\n' 
    if search in line.strip():
        file_out.write(my_line+'\n')
    else:
        file_out.write(line)

print("... done")

file_in.close()
file_out.close()

To delete from a file i just open the file, load it all into one string, and then delete what i wanted, and then save it back into the text file again. Its not that easy at all to just edit stuff halfway through a file without knowing Exactly what is going to be there.

So borrowing a bit from sneekula:

file_in = open("myfile.txt", "r")
allfile = ''
for line in file_in:
    allfile += line

allfile = allfile.replace("What you want to delete",'')
file_in.close()

file_out = open("myfile.txt",'w')
file_out.write(allfile)
file_out.close()

Kinda not on my computer at the moment so i cant test the code, but im pretty sure that should work, if not it should be close.

file_in = open("myfile.txt", "r")
allfile = ''
for line in file_in:
    allfile += line

why don't you just use allfile=file_in.read() ?

why don't you just use allfile=file_in.read() ?

I typically like to use allfile = file_in.read_lines()

This article has been dead for over six months. Start a new discussion instead.