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

标签 python file

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

12,12,12
12,31,12
1,5,3
...

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

1. 12,12,12
2. 12,31,12
...

等等。我该怎么做?

最佳答案

我知道已经有人回答了 :) 总结以上内容:

# 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

它打印在我的控制台上:

 1. 12,12,12
 2. 12,31,12
 3. 1,5,3
-----------------
['12', '12', '12']
['12', '31', '12']
['1', '5', '3']

关于python - 有没有办法读取 .txt 文件并将每一行存储到内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10393176/

相关文章:

python - 将丑陋的 csv 解析为 Pandas DataFrame 的最佳方法

python - h5py无法读取fast5文件

python - 插入带有文件特定值的换行符

java - 如何以 .jpg 文件格式从图库中获取图像?

python - Heroku 上的 webpack 和 django : bundling before collectstatic

python - AWS Systems Manager "In Progress"命令限制为 5 个?

c++ - 设置开始和结束限制以从文件中读取

android - 如何显示保存在android中的数据

python - 使用 Flask-appengine-template 时出现奇怪的 KeyProperty 失败

java - 使用java,从文件夹位置提取列表文件名的最资源有效的方法是什么