2015-10-15 31 views
0

我有一個相當簡單的問題。我在Python中定義了一個非常大的列表,如果我將它輸出到1個文本文件,文件大小將達到200mb大。我無法輕鬆打開。我可以使用Python中的filterwriter設置最大文件大小嗎?

我想知道Python中是否有任何可用的選項可以設置特定寫入文件的最大大小,並且如果超過大小可以創建一個新文件?

總結:

  • 現狀:1個文件(200MB)
  • 理想狀況:8個文件(每個25MB)

到目前爲止的代碼:

file = open("output_users.txt", "w") 
file.write("Total number of users: " + str(len(user_id))) 
file.write(str(user_id)) 
file.close() 
+0

你會在文件上手動做什麼?編輯,閱讀?如果你自己不需要這樣做,你可以使用壓縮格式。 – wap26

+0

我只需要閱讀它!一旦創建,我不需要再編輯了! @ wap26 – Rotan075

回答

1

open()中沒有內置的方法。我建議你將數據分成幾個塊,然後每個塊打開一個不同的文件。例如,假設你有超過一萬個項目(爲簡單起見,我在這裏使用整數,但它們可能是用戶記錄或你正在處理的任何項目)進行處理。你可以它們分割成十個大塊像這樣,使用itertools模塊的groupby功能,讓您的工作更容易一點:

import itertools 
original_data = range(10003) # Note how this is *not* divisible by 10 
num_chunks = 10 
length_of_one_chunk = len(original_data) // num_chunks 
chunked_data = [] 
def keyfunc(t): 
    # Given a tuple of (index, data_item), return the index 
    # divided by N where N is the length of one chunk. This 
    # will produce the value 0 for the first N items, then 1 
    # for the next N items, and so on, making this very 
    # suitable for passing into itertools.groupby. 
    # Note the // operator, which means integer division 
    return (t[0] // length_of_one_chunk) 

for n, chunk in itertools.groupby(enumerate(original_data), keyfunc): 
    chunked_data.append(list(chunk)) 

這將產生一個chunked_data名單與11的長度;每個元素都是數據項列表(在這種情況下,它們只是整數)。 chunked_data的前十項將全部具有N個項目,其中N是length_of_one_chunk(在這種情況下恰好爲1000)的值。 chunked_data的最後一個元素將是3個剩餘項目的列表,這些項目並不適用於其他列表;您可以將它們寫入單獨的文件,或者將它們追加到最後一個文件的末尾。

如果將range(10003)更改爲range(10027),則N將爲1002,最後一個元素將包含7個剩餘項目。等等。

然後你只需運行chunked_data通過一個for循環,併爲它裏面每個列表,處理數據正常,每次打開一個新的文件。你會得到你的10個文件(或8個,或者任何你設置的num_chunks)。

+0

謝謝!這會幫助我很多!感謝您的回答和明確的解釋。 – Rotan075

相關問題