A
A
albertalexandrov2018-10-15 19:44:06
Python
albertalexandrov, 2018-10-15 19:44:06

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()

As a result, the following answer is in the file:
line 1
line 2
line 3
line 4

That is, moving the pointer had no effect (or is it read-only?). Why such a conclusion?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Lisin, 2018-10-15
@BlackLacost

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="")

line 1
line 3
line 4
line 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question