Answer the question
In order to leave comments, you need to log in
Writing lines only to the end of the file?
Hello!
There is some code:
var1 = 0
var2 = 0
var3 = 0
with open(f'./tmp/tmp', 'w') as file:
file.write('line 1\n')
var1 = file.tell()
file.close()
with open('./tmp/tmp', 'a') as file:
file.write('line 2\n')
var2 = file.tell()
file.close()
with open('./tmp/tmp', 'a') as file:
file.seek(var1)
file.write('line 3\n')
file.close()
with open('./tmp/tmp', 'a') as file:
file.seek(var2, var3)
file.write('line 4\n')
file.close()
line 1
line 2
line 3
line 4
Answer the question
In order to leave comments, you need to log in
If you wanted to insert a third between the first and second lines, and the resulting third and second fourth, then this can be done like this:
with open('tmp', 'w') as file:
file.write('line 1\n')
with open('tmp', 'a') as file:
file.write('line 2\n')
with open('tmp', 'r+') as fd:
contents = fd.readlines()
contents.insert(1, 'line 3\n')
fd.seek(0)
fd.writelines(contents)
with open('tmp', 'r+') as fd:
contents = fd.readlines()
contents.insert(2, 'line 4\n')
fd.seek(0)
fd.writelines(contents)
with open('tmp') as f:
for line in f:
print(line, end="")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question