2013-07-13 30 views
0

我是編程和學習python 3.x大約3或4個月的新手。在python中,關於將數據存儲到文件中

現在,我正在試圖制定一個程序來尋找一些'魔方'的解決方案。

衆所周知,6x6魔術廣場擁有200,000,000多個解決方案。

所以,這個數字太大了正常的PC內存來存儲我想

的計算和找到的解決辦法將文件從時間存儲時間。

比方說,我想在文件成爲1,000,000時將解決方案保存到文件中。

這樣在短以下內容:

if len(resultList) == 1000000: 
    file = open('{0}x{0} PMS Solutions {1:03}.txt'.format(ansr, fileNum), 'w') 
    file.write(resultList) 
    file.close() 
    resultList = [] 

然後,當一個文件被製成,找到新的解決方案的過程中不起作用。

我的問題:

有沒有什麼辦法讓這兩個過程,計算並同時存儲工作的?

+1

看看線程模塊:http://docs.python.org/3/library/threading.html – joon

回答

1

如果您正在使用python3.3實現你想要使用什麼樣的一個簡單而優雅的方式ThreadPoolExecutor

def save_to_file(data): 
    fname = '{0}x{0} PMS Solutions {1:03}.txt'.format(ansr, fileNum) 
    with open(fname, 'w') as fout: 
     fout.write(data) # save the list to file in some way 

這樣使用它:

executor = ThreadPoolExecutor(max_workers=2) 

# ... 

if len(resultList) >= 1000000: 
    future = executor.submit(save_to_file, resultList) 
    resultList = [] 

同樣可以做到用threading模塊在3.3之前的python版本中 之類的東西:

thread = None 

if len(resultList) >= 1000000: 
    if thread is not None: 
     thread.join() # finish saving the other solutions first 
    thread = threading.Thread(target=save_to_file, args=(resultList,)) 
    thread.start() 
    resultList = []