38

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?

Gaurav Parashar
  • 1,347
  • 2
  • 19
  • 21
  • 4
    `file.readlines()` reads all the lines. That means after the first call, the file pointer is at the end of the file which causes the second and third calls to `file.readlines()` to return empty. – Hai Vu Jan 06 '18 at 04:23

2 Answers2

95

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"

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • 2
    Good solve, and thank you for the explanation of that phantom new line character! – Mike_K Feb 12 '21 at 18:38
  • 2
    why doesn't your print statement have parenthesis?? – joel.t.mathew Apr 10 '21 at 12:37
  • 3
    That because when I answered this question, I was using Python 2.7 – Hai Vu Apr 13 '21 at 05:13
  • 2
    Comma trick's clever! `line.strip()` is perhaps clearer – and `rstrip()` if you want to keep existing breaks. For those curious why that comma works: `print()` appends a line break if provided 1 arg, and a space if >1. – Leland Apr 30 '22 at 16:24
1

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 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.

Vladislav Povorozniuc
  • 2,149
  • 25
  • 26
akhilsp
  • 1,063
  • 2
  • 13
  • 26