Iterate Through a File Lines in Python [Duplicate]

Iterate Through a File Lines in Python [Duplicate]

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 For\n"
    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-Topology\n', 'Third-topology\n', 'Second-Topology\n']

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?

1

2 Answers

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 line\n"

4

Change your code like this:

file = open('topology_list.txt','r')
topology_list = file.readlines()
print content
for i in topology_list:
    print "Entered For\n"
    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.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.