迭代python中的文件行

gau*_*har 3 python

我有一个文件,其中有一些名称逐行列出.

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"

  • 那是因为当我回答这个问题时,我正在使用Python 2.7 (3认同)
  • 逗号技巧很聪明!`line.strip()` 可能更清晰 - 如果你想保留现有的中断,则使用 `rstrip()` 。对于那些好奇为什么逗号有效的人来说:如果提供了 1 个参数,`print()` 会附加一个换行符,如果 >1,则附加一个空格。 (3认同)
  • 很好的解决方案,感谢您对那个幻影新线角色的解释! (2认同)
  • 为什么你的打印语句没有括号? (2认同)