有没有一种方法可以读取一个 .txt 文件并将每一行存储到内存中?

9

我正在制作一个小程序,它可以读取并显示文档中的文本。我已经有了一个测试文件,它长这样:

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

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

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

以及其他类似的操作。我该怎么做?

8
请展示你目前的代码。 - Jordonias
1
@bjarneh readlines() 不是内存高效的。 - Ashwini Chaudhary
1
@AshwiniChaudhary 这个文件只有三行代码 :) - bjarneh
我正在尝试展示我的代码,但我不知道如何在这个网站上进行格式化。有人能帮忙吗? - EatMyApples
@VincenTTTTTTTTTTTT,请缩进您的代码,即让每行代码以4个空格或一个TAB开始。 - bjarneh
6个回答

23

我知道这个问题已经有答案了 :) 概括一下上面的内容:

# 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']

5
尝试将其存储在数组中。
f = open( "file.txt", "r" )
a = []
for line in f:
    a.append(line)

非常简单的方法来实现它!! - Surya
6
另外一种写法为 a = open("file.txt").readlines(),或等价的写法 a = list(open("file.txt"))。你应该使用 with 语句来关闭文件;这依赖于 CPython 的引用计数语义来实现,因此在 PyPy 等其他环境下表现可能与预期不同。 - Danica
如果文本文件非常大且行数较多,它是否会遇到问题? - Surya
但问题是,我有两个不同的选项,加载选项;它从文件中加载文本和显示选项,然后(在加载后)逐行“打印”所有行。 - EatMyApples
但这不会重复打印同一行吗? - EatMyApples
显示剩余3条评论

3

感谢@PePr提供的优秀解决方案。此外,您可以尝试使用内置方法String.join(data)打印.txt文件。例如:

with open(filename) as f:
    data = f.readlines()
print(''.join(data))

1
您可能也会对csv模块感兴趣。它可以让您解析、读取和写入以逗号分隔值(csv)格式存储的文件...就像您的示例一样。
示例:
import csv
reader = csv.reader( open( 'file.txt', 'rb'), delimiter=',' )
#Iterate over each row
for idx,row in enumerate(reader):
    print "%s: %s"%(idx+1,row)

0
with open('test.txt') as o:
    for i,t in enumerate(o.readlines(), 1):
        print ("%s. %s"% (i, t))

0
#!/usr/local/bin/python

t=1

with open('sample.txt') as inf:
    for line in inf:
        num = line.strip() # contains current line
        if num:
            fn = '%d.txt' %t # gives the name to files t= 1.txt,2.txt,3.txt .....
            print('%d.txt Files splitted' %t)
            #fn = '%s.txt' %num
            with open(fn, 'w') as outf:
                outf.write('%s\n' %num) # writes current line in opened fn file
                t=t+1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接