2012-05-01 7 views
5

私は、文書からテキストを読み込んで表示する小さなプログラムを作っています。私はこのようなテストファイルを持っています:.txtファイルを読み込んで各行をメモリに保存する方法はありますか?

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

などです。その上

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

と:今、私はあなたがデータを表示するように選択するときに、それはのようなシェルに表示されます、各ラインを読んで、それをメモリに保存するためにはPythonをしたいと思います。これどうやってするの?

+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

はあなたにもcsvモジュールに興味がある可能性があり、アレイに

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)形式...あなたの例は、であるように思わ内のファイルへの書き込み、あなたが解析できます

例:。

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))