I'm doing it like this now, but I want it to write at the beginning of the file instead.
f = open('out.txt', 'a') # or 'w'?
f.write("string 1")
f.write("string 2")
f.write("string 3")
f.close()
so that the contents of out.txt
will be:
string 3
string 2
string 1
and not (like this code does):
string 1
string 2
string 3
Use sed 's insert ( i ) option which will insert the text in the preceding line. Also note that some non-GNU sed implementations (for example the one on macOS) require an argument for the -i flag (use -i '' to get the same effect as with GNU sed ).
seek() method In Python, seek() function is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file.
Take a look at this question. There are some solutions there.
Though I would probably go that same way Daniel and MAK suggest -- maybe make a lil' class to make things a little more flexible and explicit:
class Prepender:
def __init__(self, fname, mode='w'):
self.__write_queue = []
self.__f = open(fname, mode)
def write(self, s):
self.__write_queue.insert(0, s)
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.__write_queue:
self.__f.writelines(self.__write_queue)
self.__f.close()
with Prepender('test_d.out') as f:
f.write('string 1\n')
f.write('string 2\n')
f.write('string 3\n')
You could throw a f.seek(0)
between each write (or write a wrapper function that does it for you), but there's no simple built in way of doing this.
EDIT: this doesn't work, even if you put a f.flush()
in there it will continually overwrite. You may just have to queue up the writes and reverse the order yourself.
So instead of
f.write("string 1")
f.write("string 2")
f.write("string 3")
Maybe do something like:
writeList = []
writeList.append("string 1\n")
writeList.append("string 2\n")
writeList.append("string 3\n")
writeList.reverse()
f.writelines(writeList)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With