Python not able to open file with non-english characters in path

前端 未结 3 643

I have a file with the following path : D:/bar/クレイジー・ヒッツ!/foo.abc

I am parsing the path from a XML file and storing it in a variable called path in the

3条回答
  •  不知归路
    2020-12-05 21:06

    Provide the filename as a unicode string to the open call.

    How do you produce the filename?

    if provided as a constant by you

    Add a line near the beginning of your script:

    # -*- coding: utf8 -*-
    

    Then, in a UTF-8 capable editor, set path to the unicode filename:

    path = u"D:/bar/クレイジー・ヒッツ!/foo.abc"
    

    read from a list of directory contents

    Retrieve the contents of the directory using a unicode dirspec:

    dir_files= os.listdir(u'.')
    

    read from a text file

    Open the filename-containing-file using codecs.open to read unicode data from it. You need to specify the encoding of the file (because you know what is the “default windows charset” for non-Unicode applications on your computer).

    in any case

    Do a:

    path= path.decode("utf8")
    

    before opening the file; substitute the correct encoding if not "utf8".

提交回复
热议问题