2012-05-01 86 views
5

我正在制作一个小程序,用于读取和显示文档中的文本。我有一个看起来像这样的测试文件:有没有办法读取.txt文件并将每行存储到内存中?

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

等等。现在我想Python来读取每一行并将其存储到内存中,所以当你选择要显示的数据,将在shell中显示它是这样:

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

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

+8

向我们展示你的代码到目前为止 – Jordonias

+3

'是pydoc file.readlines' – bjarneh

+1

@bjarneh readlines方法()不是记忆效率。 –

回答

13

我知道已经回答了:)以上概括为:

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

尝试它存储在数组

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

非常简单的做法。 – Surya

+5

也被称为'a = open(“file.txt”).readlines()',或者更加等价的'a = list(open(“file.txt”))''。你应该真的使用'with'语句来关闭文件;这依赖于CPython ref-counting语义来做到这一点,并且不会按照预期的方式运行。 PyPy。 – Dougal

+0

如果文件非常大并且文件中的行数更多,它会不会遇到问题? – Surya

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 
1

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

with open(filename) as f: 
    data = f.readlines() 
print(''.join(data)) 
相关问题