Iterate through a file lines in python

Iterate through a file lines in python

The simplest:

with open(topology_list.txt) as topo_file:
    for line in topo_file:
        print line,  # The comma to suppress the extra new line char

Yes, you can iterate through the file handle, no need to call readlines(). This way, on large files, you dont have to read all the lines (thats what readlines() does) at once.

Note that the line variable will contain the trailing new line character, e.g. this is a linen

Change your code like this:

file = open(topology_list.txt,r)
topology_list = file.readlines()
print content
for i in topology_list:
    print Entered Forn
    print i
print topology_list

When you call file.readlines() the file pointer will reach the end of the file. For further calls of the same, the return value will be an empty list.

Iterate through a file lines in python

Leave a Reply

Your email address will not be published. Required fields are marked *