简体   繁体   English

从txt python读取行

[英]Read lines from txt python

I am having a txt file and I want to read its lines in python. 我有一个txt文件,我想在python中读取它的行。 Basically I am using the following method: 基本上我使用以下方法:

f = open(description,'r')
out = f.readlines() 

for line in out:
    line

What I want is to have access in every line of the text after the for loop. 我想要的是在for循环之后访问文本的每一行。 Thus, to store lines in a matrix or something list-like. 因此,将行存储在矩阵或类似列表中。

Instead of readlines you could use 而不是你可以使用的readlines

lines = list(open(description, 'r'))

The opened file is an iterator, that yields lines. 打开的文件是一个迭代器,它产生线条。 By calling list on it, you create a list of all of them. 通过调用list上,你需要创建所有的人的名单。 There's no real need to keep the open file around in a variable, doing it this way it will be closed. 没有必要在一个变量中保持打开的文件,这样就可以关闭它。

But using readlines() to get a list is perfectly good as well. 但是使用readlines()来获取列表也是非常好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM