tags:

views:

74

answers:

3

Suppose i want to store 3 lines in a file both in python and C++ . I want to store it like this

aaa
bbb 
ccc ..

But i am giving ccc input first then bbb then aaa. How will I traverse the file from bottom to top and also store from bottom to top/?

+3  A: 

It isn't obvious from the title and question whether you want to store to a file, load from a file, or both, so I'll cover both cases:

Reading

If it's OK to load it all into memory at once (in Python):

list(reversed(list(open('foo.txt'))))

Otherwise, it gets a lot more difficult. Processing a file backwards requires that you read blocks of data a time from the end, scanning backwards through each block for newline marker, and stitching things back together at block boundaries.

Writing

If the data all fit in memory at once, put the numbers into a list (in Python):

open('foo.txt', 'w').writelines(reversed(data))

If data is an iterable, replace it with list(data).

If the data doesn't fit in memory (e.g., you have some generator that spits out a ton of data), the problem will be much harder. The simplest solution that comes to mind is to just push the data into a sqlite database and then copy it into the file. Or you might just find it easier to use the data directly from sqlite.

Marcelo Cantos
You'd need a massive file - many 100s of MB on today's low-end machines - before you couldn't load it this way
Will
And how exactly does this involve writing to a file?
Ignacio Vazquez-Abrams
Ignacio, at first I thought I'd completely misread the question, but then I realised that the title explicitly asks about traversing a file, which coloured my reading of the question. I've edited the answer to cover both cases.
Marcelo Cantos
A: 

Insert the lines to be generated at the beginning of your linear structure (list, vector<string>) each time, then iterate your structure from beginning to end.

Ignacio Vazquez-Abrams
Please don't suggest inserting at the front of a vector its O(n)
Martin York
Doesn't have to be a `vector<>`. Any linear structure that allows insertion at the beginning works.
Ignacio Vazquez-Abrams
+1  A: 

You might want to use a collections.deque. Afaik those things are optimised for insertion at one of their endpoints, so you could read your file as it is and fill the lines into a deque object with its appendleft method ... just a thought. No idea how efficient that would be. :)

jellybean