2017-11-18 121 views
0

我是Python中的一個begginer,我有一個關於文件讀取的問題: 我需要處理文件中的信息以將其寫入另一個文件中。我知道如何做到這一點,但是對於我的電腦而言,它非常耗費資源,因爲該文件非常大,但我知道它是如何格式化的! 文件遵循格式:在Python中分割多個部分的.txt文件

4 13 
9 3 4 7 
3 3 3 3 
3 5 2 1 

我不會解釋什麼是對的,因爲它會採取年齡,不會是非常有用的,但文件essentialy由四大行這樣的,一次再次。現在,我使用它來讀取文件並將其轉換在一個很長的鏈條:

inputfile = open("input.txt", "r") 
output = open("output.txt", "w") 
Chain = inputfile.read() 
Chain = Chain.split("\n") 
Chained = ' '.join(Chain) 
Chain = Chained.split(" ") 
Chain = list(map(int, Chain)) 

後來,我只是用「任務ID」對待它,但我覺得這是真的效率不高。 那麼你知道我怎麼可以將鏈分成多個知道它們是如何格式化? 感謝您的閱讀!

回答

1

如何:

res = [] 
with open('file', 'r') as f: 
    for line in f: 
    for num in line.split(' '): 
     res.append(int(num)) 

而不是讀取整個文件到內存中,您可以通過走行線。 這有幫助嗎?

如果您需要一次去4行,只需添加一個內部循環。

關於輸出,我假設你想對輸入做一些計算,所以我不一定在同一個循環中做這個。一旦完成讀取,或者不是使用列表,而是在處理輸入時使用隊列,並在此線程寫入隊列時從隊列中讀取另一個線程。

或許列表理解的工具將幫助一點,以及(我懷疑這會帶來衝擊):

res = [] 
with open('file', 'r') as f: 
    for line in f: 
    res.append(int(num) for num in line.split()) 
+0

正是我在尋找的,謝謝! –

0

也許是一行一行。這樣它消耗更少的內存。

inputfile = open("input.txt", "r") 
output = open("output.txt", "a") 

while True: 
    line = inputfile.readline() 
    numbers = words.split(" ") 
    integers = list(map(int, numbers)) 

    if not line: 
     break 

這個詞中可能有一個換行符\n。你還應該用空字符串替換它。

0

如果你不想消耗內存(可以如果文件非常大,則運行它),則需要逐行讀取留置權。

with open('input.txt', 'w') as inputfile, open('"output.txt', 'w') as output: 
    for line in inputfile: 
     chain = line.split(" ") 
     #do some calculations or what ever you need 
     #and write those numbers to new file 
     numbers = list(map(int, chain)) 
     for number in numbers 
      output.write("%d " % number) 
1

嗯有寫入到一個文件中的一些方法沒有閱讀它,我相信

Add text to end of line without loading file

https://docs.python.org/2.7/library/functions.html#print

from __future__ import print_function 
# if you are using python2.7 
i = open("input","r") 
f = open("output.txt","w") 
a = "awesome" 
for line in i: 
    #iterate lines in file input 
    line.strip() 
    #this will remove the \n in the end of the string 
    print(line,end=" ",file=f) 
    #this will write to file output with space at the end of it 

這可能幫助,我是一個新手太多,但更好的谷歌富士XD