在Python中逐行读取.txt文件

5

我的.txt文件看起来像这样:

![enter image description here][1]

如何将我的txt文件读入字符串对象中,以相同的格式打印出来?

I have tried: 
    with open ("/Users/it/Desktop/Classbook/masterClassList.txt", "r") as myfile:
    data = myfile.read()

for item in data:
    print item

这段代码会将每个字符都打印在新的一行。为了调用字符串方法,特别是'string.startswith()',我需要将txt文件作为字符串处理。

从我的IDE控制台可以看到,在每行内容之间都有一个黑色的空行。我该如何消除这些空行?

以下是我的解决方案:

with open ("/Users/it/Desktop/Classbook/masterClassList.txt", "r") as myfile:
    data = myfile.read()
    for line in data:
        line.rstrip()

print data
2个回答

9

4

最简单的可能是:

data = myfile.readlines()

这将与您的其余代码一起工作--或者,您可以直接在with内部循环myfile(内部:-),这样您将一次获取一行。请注意,行包括结束\n,因此您可能希望在打印和其他操作之前使用.strip()对它们进行处理:-)


谢谢@Alex Martelli,请参考我上面的编辑。 - Philip McQuitty
@PhilipMcQuitty已经解决了这个问题,请在字符串上调用.strip() - Ryan Haining

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接