I have a txt
file that looks like this:
112
I just want to add 1
to that line using a Python command. Any ideas?
I have a txt
file that looks like this:
112
I just want to add 1
to that line using a Python command. Any ideas?
This feels too much like a learning / homework effort, so let's not ruin that for you:
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.
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')