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?
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.
You need to refill the source with 'data' and then you can work with the same data again.
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.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With