Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write() at beginning of file?

Tags:

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
like image 986
kristus Avatar asked Apr 20 '10 18:04

kristus


People also ask

How do I add a line to the beginning of a file in Unix?

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

How do I put text in a specific position of a file in Python?

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.


2 Answers

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')
like image 86
ktdrv Avatar answered Oct 07 '22 04:10

ktdrv


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)
like image 21
Daniel DiPaolo Avatar answered Oct 07 '22 04:10

Daniel DiPaolo