2013-08-01 43 views
2

我正在學習如何將字符串,列表等寫入txt/dat文件。我想在我的代碼中添加註釋,以便我可以參考訪問密鑰的內容。所以這就是我所做的。Python - 試圖添加註釋時出錯

# Mode Description 
# rb  Read from a binary file. If the file doesn’t exist, Python will complain with an error. 
# wb  Write to a binary file. If the file exists, its contents are overwritten. If the file doesn’t exist, 
#  it’s created. 
# ab  Append a binary file. If the file exists, new data is appended to it. If the file doesn’t exist, it’s 
#  created. 
# rb+ Read from and write to a binary file. If the file doesn’t exist, Python will complain with an 
#  error. 
# wb+ Write to and read from a binary file. If the file exists, its contents are overwritten. If the file 
#  doesn’t exist, it’s created. 
# ab+ Append and read from a binary file. 

後,我有:

import pickle, shelve 

print("Pickling lists.") 
variety = ["sweet", "hot", "dill"] 
shape = ["whole", "spear", "chip"] 
brand = ["Claussen", "Heinz", "Vlassic"] 

f = open("pickles1.dat", "wb") 

pickle.dump(variety, f) 
pickle.dump(shape, f) 
pickle.dump(brand, f) 
f.close() 

print("\nUnpickling lists.") 
f = open("pickles1.dat", "rb") 
variety = pickle.load(f) 
shape = pickle.load(f) 
brand = pickle.load(f) 

print(variety) 
print(shape) 
print(brand) 
f.close() 

當我運行它,我得到以下錯誤:

語法錯誤:非UTF-8編碼與 '\ X92' 文件PickleIt開始.py在第10行,但沒有聲明編碼;詳情請見http://python.org/dev/peps/pep-0263/

我查了一下鏈接,但是我真的不明白,以前我沒看過。


哦和道歉線10 # rb

+1

刪除評論中的'apostrophes'然後再試 – suhailvs

+0

哇,固定它,謝謝。我刪除並替換了它們。這是否意味着python或ide沒有識別出我複製過的? – mccdlibby

+0

它不是'utf-8'支持的字符,我認爲它是'ascii'或者什麼 – suhailvs

回答

6

將所有替換爲'。 這是抱怨,因爲你沒有將編碼類型添加到文件的開頭。默認編碼是utf-8,其中不允許這些字符。

而不是取代的,你可以加入這一行開始(評論前):

# coding: iso-8859-1

(或其他編碼,其中這些字符都存在,像latin-1例如。)

該行設置文件的編碼並允許使用特殊字符。

+0

謝謝,這有很大的幫助。 – mccdlibby

+0

@mccdlibby很高興我可以幫助:) – koplersky

2

與您的意見正規報價'更換智能引號

0

這個角色似乎是問題」