有没有办法读取.txt文件并将每一行存储到内存?

Eat*_*les 7 python file

我正在制作一个小程序,它将从文档中读取和显示文本.我有一个看起来像这样的测试文件:

12,12,12
12,31,12
1,5,3
...
Run Code Online (Sandbox Code Playgroud)

等等.现在我希望Python读取每一行并将其存储到内存中,因此当您选择显示数据时,它将在shell中显示它:

1. 12,12,12
2. 12,31,12
...
Run Code Online (Sandbox Code Playgroud)

等等.我怎样才能做到这一点?

pep*_*epr 20

我知道它已经回答了:)总结一下上面的内容:

# It is a good idea to store the filename into a variable.
# The variable can later become a function argument when the
# code is converted to a function body.
filename = 'data.txt'

# Using the newer with construct to close the file automatically.
with open(filename) as f:
    data = f.readlines()

# Or using the older approach and closing the filea explicitly.
# Here the data is re-read again, do not use both ;)
f = open(filename)
data = f.readlines()
f.close()


# The data is of the list type.  The Python list type is actually
# a dynamic array. The lines contain also the \n; hence the .rstrip()
for n, line in enumerate(data, 1):
    print '{:2}.'.format(n), line.rstrip()

print '-----------------'

# You can later iterate through the list for other purpose, for
# example to read them via the csv.reader.
import csv

reader = csv.reader(data)
for row in reader:
    print row
Run Code Online (Sandbox Code Playgroud)

它在我的控制台上打印:

 1. 12,12,12
 2. 12,31,12
 3. 1,5,3
-----------------
['12', '12', '12']
['12', '31', '12']
['1', '5', '3']
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试将其存储在一个数组中

f = open( "file.txt", "r" )
a = []
for line in f:
    a.append(line)
Run Code Online (Sandbox Code Playgroud)

  • 也称为`a = open("file.txt").readlines()`,或更等效的`a = list(open("file.txt"))`.你应该真的使用`with`语句来关闭文件; 这依赖于CPython引用计数语义,并且不会像PyPy那样按预期运行. (5认同)