【发布时间】:2015-01-20 16:24:12
【问题描述】:
我在 linux 中编写了一个 python 2.7 代码,它运行良好。
它使用
os.listdir(os.getcwd())
将文件夹名称作为变量读取并稍后在某些部分使用它们。
在 linux 中,我使用简单的转换技巧将非 asci 字符手动转换为 asci 字符。
str(str(tfile)[0:-4]).replace('\xc4\xb0', 'I').replace("\xc4\x9e", 'G').replace("\xc3\x9c", 'U').replace("\xc3\x87", 'C').replace("\xc3\x96", 'O').replace("\xc5\x9e", 'S') ,str(line.split(";")[0]).replace(" ", "").rjust(13, "0"),a))
这种方法在 Windows 中失败了。我试过了
udata = str(str(str(tfile)[0:-4])).decode("UTF-8")
asci = udata.encode("ascii","ignore")
以下也失败了
DEM¦-RTEPE # at this string error occured
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:\Users\benhur.satir\workspace\Soykan\tkinter.py", line 178, in SparisDerle
udata = str(str(str(tfile)[0:-4])).decode("utf=8")
File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa6 in position 3: invalid start byte
如何在 Windows 中处理此类字符?
注意:将它们保留为 UTF 会导致 xlswriter 模块失败,因此我需要将它们转换为 asci。缺少字符是不可取的,但也可以接受。
【问题讨论】:
-
os.listdir(os.getcwdu())(注意“u”)会将名称列为 unicode 字符串。 -
谢谢这一切都解决了。任何面临同样情况的人,也请看一下“ftfy”库。将它与 os.getcwdu() 结合起来就完成了!
标签: python windows python-2.7