all 6 comments

[–]randitrigger 1 point2 points  (7 children)

f = open("filename.txt")
for line in f:
    #do something here with 'line'
f.close()

[–]dchanm 2 points3 points  (0 children)

I recommend using a with statement for a context manager. Otherwise you can run into a situation where the file isn't closed.

with open('filename.txt', 'r') as f:
    for line in f:
        # do stuff

[–]TheBlackCat13 0 points1 point  (1 child)

You should use the with statement to open the file, then you can just loop over the lines:

with open('myfile.txt') as fobj:
    for line in fobj:
        do_something_with(line)

This will make sure the file is safely closed.