1

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.

2
  • 1
    how is it hard to test yourself? Commented Jul 7, 2010 at 22:23
  • 1
    Maybe you should take a step back and check how lists work in python in the first place. There is absolutely no need for a list to contain an item indicating you are at its end. Commented Jul 7, 2010 at 23:37

3 Answers 3

5

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.