Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a file lines in python [duplicate]

Tags:

python

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?

like image 366
Gaurav Parashar Avatar asked Jan 06 '18 04:01

Gaurav Parashar


People also ask

How do you iterate through a file line by line in Python?

To read a file word by word in Python, you can loop over each line in a file and then get the words in each line by using the Python string split() function.

How do I read the same file twice in Python?

You need to refill the source with 'data' and then you can work with the same data again.

How do you duplicate a line in Python?

Alternatively, you can press Ctrl+Shift+A , start typing the command name in the popup, and then choose it there. The duplicated line or multi-line selection is inserted below the original line or selection; the duplicated inline selection is inserted to the right of the original.


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"

like image 144
Hai Vu Avatar answered Sep 30 '22 21:09

Hai Vu


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.

like image 42
akhilsp Avatar answered Sep 30 '22 19:09

akhilsp