Home > Mobile >  How to edit a line of a text file in python
How to edit a line of a text file in python

Time:05-31

I am really sorry for the simple question. But i have forgotten how to edit a line of a text file. Basically I have a text file that looks like this:

112

I just want to add 1 to that line using a python command. Any ideas?

CodePudding user response:

This feels too much like a learning / homework effort, so let's not ruin that for you:

  1. You read all lines before the line you want to edit, and write them to a temporary output file
  2. you read the line, append your 1, and write it to your temporary output file
  3. You read all lines after the line you want to edit, and write them to a temporary output file
  4. You close the input file, unlink/delete it and rename the temporary file so that it replaces the original file.

You can alternatively edit the file in-place, but it will require you to first read all the lines after the line you want to edit into a temporary buffer, then modify the line, then overwrite everything after the modified positions back.

Files have no notion of "lines". They deal in bytes. If you need to insert a byte somewhere in the file, you need to move everything after that byte's position backwards.

CodePudding user response:

You should read the file, replace the line and rewrite the file domething like :

with open('file.txt', 'r') as file :
  filedata = file.read()
 
filedata = filedata.replace('112', '1112')
 
with open('file.txt', 'w') as file:
  file.write(filedata)

if you want add 1 to all line you can use something to modify all lines like:

with open('file.txt', 'r') as file :
  filedata = file.read()

list_num = []
for num in  filedata.split('\n')[:-1]:
    list_num.append(str(int(num) 1))

'\n'.join(list_num)
with open('file.txt', 'w') as file:
  file.write('\n'.join(list_num)   '\n')    
  • Related