因此,几天来我一直在为这个问题苦思冥想,但就是想不通。我读过 this , this和 this感觉我一定是错过了什么。
我正在尝试使用以下代码将具有复杂 unicode 标题的简单文本文件复制到临时文件夹中:
self._temp_path = tempfile.mkdtemp()
self.src = os.path.join(self._temp_path, 'src')
os.makedirs(self.src)
self.dst = os.path.join(self._temp_path, 'dst')
os.makedirs(self.dst)
self.dirname = dirname = os.path.join(os.path.dirname(__file__), 'testfiles')
f = u'file-\xe3\x82\xa8\xe3\x83\xb3\xe3\x83\x89\xe3\x83\xac\xe3\x82\xb9.txt'
src = os.path.join(dirname, f)
dst = os.path.join(self.src, f)
shutil.copy2(src, dst)
我在执行测试时收到以下消息:
s = '/tmp/tmpc1gzwf/src/file-ã¨ã³ãã¬ã¹.txt'
> st = os.stat(s)
E UnicodeEncodeError: 'ascii' codec can't encode characters in position 24-38: ordinal not in range(128)
我试过同时使用 shutil.copy 和 shutil.copy2,它们产生了相同的结果。我也试过改变:
shutil.copy2(src, dst)
到:
shutil.copy2(src.encode('utf-8'), dst.encode('utf-8'))
但是由于编码破坏了文件名,这导致了这个错误消息:
src = '/home/phil/projects/unicode_copy/tests/testfiles/file-\xc3\xa3\xc2\x82\xc2\xa8\xc3\xa3\xc2\x83\xc2\xb3\xc3\xa3\xc2\x83\xc2\x89\xc3\xa3\xc2\x83\xc2\xac\xc3\xa3\xc2\x82\xc2\xb9.txt'
dst = '/tmp/tmpCsb3qW/src/file-\xc3\xa3\xc2\x82\xc2\xa8\xc3\xa3\xc2\x83\xc2\xb3\xc3\xa3\xc2\x83\xc2\x89\xc3\xa3\xc2\x83\xc2\xac\xc3\xa3\xc2\x82\xc2\xb9.txt'
def copyfile(src, dst):
...
> with open(src, 'rb') as fsrc:
E IOError: [Errno 2] No such file or directory: '/home/phil/projects/unicode_copy/tests/testfiles/file-\xc3\xa3\xc2\x82\xc2\xa8\xc3\xa3\xc2\x83\xc2\xb3\xc3\xa3\xc2\x83\xc2\x89\xc3\xa3\xc2\x83\xc2\xac\xc3\xa3\xc2\x82\xc2\xb9.txt'
在代码中的不同点尝试了许多其他的 encode() 和 decode() 组合后,我放弃了。声明 unicode 文件名并将其传递给 shutil.copy 的正确方法是什么?
请您参考如下方法:
我根据您的代码在我的系统上快速运行了以下代码,它似乎运行良好:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
import tempfile
from pathlib import Path
class Code():
def run(self):
self._temp_path = Path(tempfile.mkdtemp())
self.dstdir = self._temp_path / 'dst'
os.makedirs(self.dstdir)
self.srcdir = Path(os.path.dirname(__file__)) / 'testfiles'
filename = u'file-\xe3\x82\xa8\xe3\x83\xb3\xe3\x83\x89\xe3\x83\xac\xe3\x82\xb9.txt'
self.srcpath = self.srcdir / filename
self.dstpath = self.dstdir / filename
with open(self.srcpath, 'w') as f:
f.write('test')
shutil.copy2(self.srcpath, self.dstpath)
if __name__ == '__main__':
code = Code()
code.run()
print(code.dstpath)
示例输出为 /tmp/tmpgqwktb_v/dst/file-ã¨ã³ãã¬ã¹.txt。
可能的原因是:
- 我正在使用 Python3,它对 unicode 的支持明显更好
- 我在 en_GB.UTF-8 语言环境中运行 Linux
- 我的脚本的第二行,声明源的编码
也许与您的环境的差异可以解释您的错误。
希望这对您有所帮助!
