python3.5 open file with latin1 character on name

时间:2016-08-31 17:33:22

标签: python-3.x directory pathlib

I have a file called "não.mp3", when I try to open it with pathlib, the name is converted to "nao.mp3", since there is no such file in the folder, python returns an error:

>>> p = Path("D:/não.mp3")
>>> p
WindowsPath('D:/nao.mp3')
>>> p.exists()
False
>>> with p.open() as f: f.readline()
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\everton\AppData\Local\Programs\Python\Python35\lib\pathlib.py", line 1136, in open
    opener=self._opener)
  File "C:\Users\everton\AppData\Local\Programs\Python\Python35\lib\pathlib.py", line 992, in _opener
    return self._accessor.open(self, flags, mode)
  File "C:\Users\everton\AppData\Local\Programs\Python\Python35\lib\pathlib.py", line 371, in wrapped
    return strfunc(str(pathobj), *args)
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\nao.mp3'

1 个答案:

答案 0 :(得分:0)

Unfortunately, it looks like you're going to have to pass the Unicode code-point as part of your string. The code-point for ã is '00E3' Try this:

p = Path("D:/n\u00e3o.mp3")

When doing this on Windows 10 (and having a corresponding file), I get

>>> p.exists()
True

It doesn't look like pathlib handles unicode characters in the way you expect. You could try another library, like os or shutil.

os.listdir can give you all of the filenames in a directory if you give it the directory name as a bytes b'':

>>> os.listdir(b'D:/')
[b'n\xe3o.mp3']

Using this, you can get a list of all your files that you can use to build paths. You can convert the bytes object back to a string by using bytes_object.decode('latin-1')