簡體   English   中英

Python-3x Unicode打印與寫入

[英]Python-3x Unicode Print vs Write

我創建了以下程序來嘗試解決我認為是unicode的問題:

s = '7/02/16;07:30:00;São Paulo-8;Reachability: 18.5%'
s_type = type(s)
print ("variable s contains: ",s)
print ("variable s type is: ", s_type)
text_file = open("test_file.txt", "w")
text_file.write(s)
text_file.close()

程序運行時,print語句提供以下輸出:

variable s contains:  7/02/16;07:30:00;São Paulo-8;Reachability: 18.5%
variable s type is:  <class 'str'>

當需要寫入文件時,出現以下錯誤:

Traceback (most recent call last):
  File "/Users/tglund/Projects/Python/thousandeyes/unicode.py", line 6, in <module>
     text_file.write(s)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe3' in position 18: ordinal not in range(128)

我已經從https://docs.python.org/3/howto/unicode.html從頭到尾閱讀了unicode文檔。

但尚未成功破解代碼。

我可以復制分配給變量s的字符串並將其粘貼到文件中,保存文件,然后“更多”文件。 我在Mac上,該字符串正確顯示在屏幕上。 Python打印語句正確顯示了字符串。

我所有這些的目標是創建一個定界符為“;”的csv文本文件。 問題似乎是位置字段中帶重音符號的第二個字符。 對於字符串s包含以下字段:日期,地點,信息

在解決問題方面的任何幫助將不勝感激。

即使在具有不同默認值的系統上,也可以通過以下方式重現您的錯誤:

text_file = open("test_file.txt", "w", encoding='ascii')
text_file.write('\xe3')

問題是您的默認文本編碼為ascii。 或者至少這就是Python所理解的。 請參見open()下的“ encoding”和locale.getpreferredencoding()

解決此問題的最簡單方法是告訴Python使用兼容的編碼打開文件。 例如UTF-8(因為您的字符是Unicode編碼的):

text_file = open("test_file.txt", "w")
# Becomes
text_file = open("test_file.txt", "w", encoding='utf_8')

並且應該完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM