Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有办法读取.txt文件并将每一行存储到内存中?_Python_File - Fatal编程技术网

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

Python 有没有办法读取.txt文件并将每一行存储到内存中?,python,file,Python,File,我正在制作一个小程序,可以读取和显示文档中的文本。我有一个测试文件,如下所示: 12,12,12 12,31,12 1,5,3 ... 等等。现在,我希望Python读取每一行并将其存储到内存中,因此当您选择显示数据时,它将在shell中显示如下内容: 1. 12,12,12 2. 12,31,12 ... 等等。如何执行此操作?尝试将其存储在阵列中 f = open( "file.txt", "r" ) a = [] for line in f: a.append(line) 您

我正在制作一个小程序,可以读取和显示文档中的文本。我有一个测试文件,如下所示:

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

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

等等。如何执行此操作?

尝试将其存储在阵列中

f = open( "file.txt", "r" )
a = []
for line in f:
    a.append(line)

您可能还对
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)

我知道已经有答案了:)总结一下上述内容:

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

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

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

让我们看看你的代码,这样far@bjarnehreadlines()的内存效率不高。@AshwiniChaudhary文件只有3行:)我正试图向你们展示我的代码,但我不知道如何在这个网站上格式化它。有人能帮我吗?@Vincentttttt缩进你的代码,即让代码的每一行以4个空格或一个制表符开头。非常简单的方法。!!也称为
a=open(“file.txt”).readlines()
,或更等效的
a=list(open(“file.txt”)
。您确实应该使用
with
语句来关闭文件;这依赖于CPython ref counting语义来实现,在例如PyPy下不会像预期的那样运行。如果文本非常大,文件中的行数更多,它不会遇到问题吗?但问题是,我有两个不同的选项,加载选项;从文件中加载文本,然后(加载后)“打印”所有行的显示选项仅在数组
a
中循环以打印出您的行,即
a[0]
以显示第1行
#!/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
with open(filename) as f:
    data = f.readlines()
print(''.join(data))