tags:

views:

69

answers:

3

When you use the fileName.readlines() function in Python, is there a symbol for the end of the file that is included in the list?

For example, if the file is read into a list of strings and the last line is 'End', will there be another place in the list with a symbol indicating the end of the file?

Thanks.

A: 

It simply returns a list containing each line -- there's no "EOF" item in the list.

Faisal
+5  A: 

No, the list contains one element for each line in the file.

You can do something with each line in a for look like this:

lines = infile.readlines()
for line in lines:
    # Do something with this line
    process(line)

Python has a shorter way of accomplishing this that avoids reading the whole file into memory at once

for line in infile:
    # Do something with this line
    process(line)

If you just want the last line of the file

lines = infile.readlines()
last_line = lines[-1]

Why do you think you need a special symbol at the end?

gnibbler
+1  A: 

The list returned by .readlines(), like any other Python list, has no "end" marker -- assumin e.g. you start with L = myfile.readlines(), you can see how many items L has with len(L), get the last one with L[-1], loop over all items one after the other with for item in L:, and so forth ... again -- just like any other list.

If for some peculiar reason you want, after the last line, some special "sentinel" value, you could for example do L.append('') to add just such a sentinel, or marker -- the empty string is never going to be the value of any other line (since each item is a complete line including the trailing '\n', so it will never be an empty string!).

You could use other arbitrary markers, such as None, but often it's simpler, when feasible [[and it's obviously feasible in this case, as I've just shown]], if the sentinel is of exactly the same type as any other item. That depends on what processing you're doing that needs a past-the-end "sentinel" (I'm not going to guess because you give us no indication, and only relatively rare problems are best solved that way in Python, anyway;-), but in almost every conceivable case of sentinel use a '' sentinel will be just fine.

Alex Martelli