Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text to end of line without loading file

Tags:

python

I need to store information into a very big file, in form of many dictionaries. That's not so important, is just to say that I tried to first get all the data into these dictionaries and I run out of memory (~60Gb).

Fine, so I want to add the data in the file without actually loading it in memory, by doing a loop on the lines and attaching to each line a bit of text. Is that possible? if so, how?

like image 573
chuse Avatar asked Dec 16 '14 15:12

chuse


People also ask

How do I add an end of line character in a text file?

You can add end-of-line characters by using a program or script, or by adding a newline field in a SELECT statement. To add an end-of-line character, you can write the fixed-length records to a data file and then modify the data file with a program or script.

How do you append to top of file in Python?

Open the first file in append mode and the second file in read mode. Append the contents of the second file to the first file using the write() function. Reposition the cursor of the files at the beginning using the seek() function. Print the contents of the appended files.


1 Answers

Did you try any code yourself at all, what were your findings? You might go along the following approach:

with open('/tmp/bigfile.new', 'w') as output:
    with open('/tmp/bigfile', 'r') as input:
        while True:
            line = input.readline().strip()
            if not line:
                break
            line += ' Look ma, no hands!'
            print(line, file=output)

Except of course that instead of 'look ma no hands' you'd have your extra dictionary ;-)

like image 67
Karel Kubat Avatar answered Sep 28 '22 11:09

Karel Kubat