我有一个文件,其中有一些名称逐行列出.
gparasha-macOS:python_scripting gparasha$ cat topology_list.txt
First-Topology
Third-topology
Second-Topology
Run Code Online (Sandbox Code Playgroud)
现在我试图迭代这些内容,但我无法这样做.
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
Run Code Online (Sandbox Code Playgroud)
file.readlines()以列表形式打印文件的行.所以我得到了这个:
['First-Topology\n', 'Third-topology\n', 'Second-Topology\n']
Run Code Online (Sandbox Code Playgroud)
但是,当我遍历此列表时,我无法这样做.
此外,当我将它分配给变量'topology_list'时,如倒数第二行并打印它.它给了我一个空列表.
[]
Run Code Online (Sandbox Code Playgroud)
所以我有两个问题.
我的做法有什么问题?怎么做到这一点?
Hai*_* Vu 14
最简单的:
with open('topology_list.txt') as topo_file:
for line in topo_file:
print line, # The comma to suppress the extra new line char
Run Code Online (Sandbox Code Playgroud)
是的,您可以遍历文件句柄,无需调用readlines().这样,在大文件上,您不必一次读取所有行(这就是做什么readlines()).
请注意,line变量将包含尾随的新行字符,例如"this is a line \n"