Iterate through a file lines in python

Question:

I have a file which have some names listed line by line.

gparasha-macOS:python_scripting gparasha$ cat topology_list.txt 
First-Topology
Third-topology
Second-Topology

Now I am trying to iterate through these contents, but I am unable to do so.

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

topology_list = file.readlines()
print topology_list

file.readlines() prints the lines of the files as a list.
So I am getting this:

 ['First-Topologyn', 'Third-topologyn', 'Second-Topologyn']

However, When i iterate through this list, I am unable to do so.

Also, when I assign it to a variable ‘topology_list’ as in the penultimate line and print it. It gives me an empty list.

[]

So I have two questions.

What is wrong with my approach?
How to accomplish this?

Asked By: Gaurav Parashar

||

Answers:

Change your code like this:

file = open('topology_list.txt','r')
topology_list = file.readlines()
print topology_list
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.

Answered By: akhilsp

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 don’t have to read all the lines (that’s what readlines() does) at once.

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

Answered By: Hai Vu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.