1

ファイルを開こうとしていますが、py がユーザー名に問題があることに気付きました (ロシア語です)。アイドルを幸せにするためにこれを適切にデコード/エンコードする方法に関する提案はありますか?

私はpy 2.6.5を使用しています

xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r")

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    xmlfile = open(str(u"D:\\Users\\Эрик\\Downloads\\temp.xml"), "r")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128)

os.sys.getfilesystemencoding() 'mbcs'

xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r")

トレースバック (最新の呼び出しが最後): ファイル ""、1 行目、xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r") IOError: [ Errno 22] 無効なモード ('r') またはファイル名: 'D:\Users\Y?ee\Downloads\temp.xml'

4

2 に答える 2

0

r"raw quote"最初の問題は、プレフィックスを使用しない限り、パーサーが文字列内のバックスラッシュを解釈しようとすることです。2.6.5 では、Unicode 文字列を特別に扱う必要はありませんが、ソース コードで次のようなファイル エンコーディング宣言が必要になる場合があります。

# -*- coding: utf-8 -*-

PEP 263で定義されています。インタラクティブに動作する例を次に示します。

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2
>>> f = r"D:\Users\Эрик\Downloads\temp.xml"
>>> f
'D:\\Users\\\xd0\xad\xd1\x80\xd0\xb8\xd0\xba\\Downloads\\temp.xml'
>>> x = open(f, 'w')
>>> x.close()
>>> 
$ ls D*
D:\Users\Эрик\Downloads\temp.xml

はい、これは Unix システム上にあるため\意味がなく、端末のエンコーディングは utf-8 ですが、動作します。ファイルを読み取るときに、パーサーにコーディングのヒントを与える必要がある場合があります。

于 2010-06-20T18:27:58.123 に答える
0

最初の問題:

xmlfile = open(u"D:\\Users\\Эрик\\Downloads\\temp.xml", "r")
### The above line should be OK, provided that you have the correct coding line
### For example # coding: cp1251

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    xmlfile = open(str(u"D:\\Users\\Эрик\\Downloads\\temp.xml"), "r")
### HOWEVER the above traceback line shows you actually using str()
### which is DIRECTLY causing the error because it is attempting
### to decode your filename using the default ASCII codec -- DON'T DO THAT.
### Please copy/paste; don't type from memory.
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128)

2番目の問題:

os.sys.getfilesystemencoding()生産する'mbcs'

xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r")
### (a) \t is interpreted as a TAB character, hence the file name is invalid.
### (b) encoding with mbcs seems not to be useful; it messes up your name ("Y?ee").

Traceback (most recent call last):
File "", line 1, in xmlfile = open(u"D:\Users\Эрик\Downloads\temp.xml".encode("mbcs"), "r")
IOError: [Errno 22] invalid mode ('r') or filename: 'D:\Users\Y?ee\Downloads\temp.xml'

Windows でファイル名をハードコーディングする際の一般的なアドバイス(優先度の高い順):

(1) 禁止
(2)/例を使用"c:/temp.xml"
(3) バックスラッシュ付きの生の文字列を使用r"c:\temp.xml"
(4) バックスラッシュを 2 つ使用"c:\\temp.xml"

于 2010-06-20T22:14:38.867 に答える