有没有办法读取.txt文件并将每一行存储到内存中? [英] Is there a way to read a .txt file and store each line to memory?

查看:130
本文介绍了有没有办法读取.txt文件并将每一行存储到内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a little program that will read and display text from a document. I have got a test file which looks like this:

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

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

and so on. Now I would like Python to read each line and store it to memory, so when you select to display the data, it will display it in the shell as such:

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

,依此类推.我该怎么办?

and so on. How can I do this?

推荐答案

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

I know it is already answered :) To summarize the above:

# 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

它会在我的控制台上打印:

It prints on my console:

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

这篇关于有没有办法读取.txt文件并将每一行存储到内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆