2016-03-07 53 views
1

我使用Python 2.7有沒有辦法自動創建包含來自不同文件的字典的新文本文件?

在這裏,我創建了一套詞典:

day0 = 0 
    day1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
      11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 
      21, 22, 23, 24, 25] 

    month0 = 0 
    december = [day0, day1] 

    calendar = [month0, december] 

那我想做的事是這樣的:

file = open("calendarScript.py", "w") 
    file.write(calendar) ## Trying to create the calendar in a new doc 
    file.close() 

但我得到這個錯誤:

TypeError: expected a string or other character buffer object 

有沒有辦法在新文檔中重新創建字典? 謝謝您的幫助:)

PS,我只是嘗試這樣做:

import shutil 

    shutil.copy(calendar, newFolder) 

而且回來了這個錯誤:

TypeError: coercing to Unicode: need string or buffer, list found 

試圖找到一種方法,一個字典複製到新文件。

+0

我不認爲你有什麼想出一本字典是什麼。 – jonrsharpe

+0

首先,你必須閱讀關於什麼[字典](https://docs.python.org/2/tutorial/datastructures.html#dictionaries)實際上是 – Idos

+0

我從Zed Shaw在Learn Python the Hard Way(http: //learnpythonthehardway.org/book/ex39.html)。我認爲字典是這樣的:calendar = [month0,12月] ...然後可以這樣調用:calendar [1] ...然後我會得到12月的內容。 – travis

回答

0

我的問題的答案是「轉儲」。我試圖做的是「轉儲」到一個文本文件。由於@KFL此響應(下面的鏈接):

Writing a dict to txt file and reading it back?

>>> import json 
    >>> d = {"one":1, "two":2} 
    >>> json.dump(d, open("text.txt",'w')) 

他還回答了什麼事情是我的下一個問題:

>>> d2 = json.load(open("text.txt")) 
    >>> print d2 
    {u'two': 2, u'one': 1} 
相關問題