tags:

views:

123

answers:

2

How do you read a character by character from a source file in python until end of line and how do you check for end of line in python so that you can then start reading from the next line and finally how do we check for the end of file condition to finish the read in the entire file. Thank You:).

+4  A: 

You can simply iterate over each line in Python. Use the universal end-of-line mode if you want Python to care about Windows/UNIX/Mac line ends automatically:

with open("mytextfile.txt", "rtU") as f:
  for line in f:
    # Now you have one line of text in the variable "line" and can
    # iterate over its characters like so:
    for ch in line:
      ... # do something here

You won't have to care about EOL/EOF yourself in this example code.

Note that the line variable includes line endings. If you don't want them, you could use line = line.rstrip(), for example.

AndiDog
Thank you Sir:)
mgj
A: 

You don't have to worry about line and file endings, just do

file = open('yourfile', 'r')
for line in file.readlines():
    for c in line:
        # do sth.
jellybean
in newer versions of python, file objects are iterators over lines. this means you can avoid the call to `readlines()`, and thus avoid storing the whole file in memory. the second line then becomes:`for line in file:`
Adrien Plisson
Thank you Sir:)
mgj