在Python中逐行读取.txt文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27577435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:58:05  来源:igfitidea点击:

Read .txt file line by line in Python

pythonstringreadfilestring-split

提问by Philip McQuitty

My .txt file looks like this:

我的 .txt 文件如下所示:

![enter image description here][1]

![在此处输入图像描述][1]

How can I read my txt file into a string object that can be printed in the same format as above?

如何将我的 txt 文件读入可以以与上述相同格式打印的字符串对象中?

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

for item in data:
    print item

This code prints every character on a new line. I need the txt file to be a string in order to call string methods, particularly 'string.startswith()'

此代码在新行上打印每个字符。我需要 txt 文件是一个字符串才能调用字符串方法,特别是 'string.startswith()'

As you can see, in my IDE console, the lines are printing with a black line of spaces in between each line of content. How can I eliminate these blank lines?

如您所见,在我的 IDE 控制台中,每行内容之间都打印有黑色空格线。我怎样才能消除这些空行?

Here is my working solution:

这是我的工作解决方案:

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

print data

采纳答案by Alex Martelli

Simplest might be:

最简单的可能是:

data = myfile.readlines()

This would work w/the rest of your code -- or, you could loop directly on myfile (insidethe with:-) and you'd be getting one line at a time. Note that lines include the ending \nso you may want to .strip()them before printing &c:-)

这将适用于您的其余代码 - 或者,您可以直接在 myfile 上循环(在 :- 内)with并且一次只能得到一行。请注意,行包括结尾,\n因此您可能需要.strip()在打印 &c 之前使用它们 :-)

回答by Dmitry Wojciechowski

The most memory efficient way of reading lines is:

读取行的最有效的内存方式是:

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

i.e. you don't need to read the entire file in to a memory, only line by line. Here is the link to python tutorial: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

即您不需要将整个文件读入内存,只需一行一行。这是 python 教程的链接:https: //docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects