Python:复制路径中含特殊字符的文件

3 投票
3 回答
7775 浏览
提问于 2025-04-15 23:14

在Python 2.5中,有没有办法复制路径中包含特殊字符(比如日文字符、俄文字母)的文件?shutil.copy这个方法无法处理这些情况。

这里有一些示例代码:

import copy, os,shutil,sys
fname=os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt"
print fname
print "type of fname: "+str(type(fname))
fname0 = unicode(fname,'mbcs')
print fname0
print "type of fname0: "+str(type(fname0))
fname1 = unicodedata.normalize('NFKD', fname0).encode('cp1251','replace')
print fname1
print "type of fname1: "+str(type(fname1))
fname2 = unicode(fname,'mbcs').encode(sys.stdout.encoding)
print fname2
print "type of fname2: "+str(type(fname2))

shutil.copy(fname2,'C:\\')

这是在俄罗斯的Windows XP上运行的输出结果:

C:\Documents and Settings\└фьшэшёЄЁрЄюЁ\Desktop\testfile.txt
type of fname: <type 'str'>
C:\Documents and Settings\Администратор\Desktop\testfile.txt
type of fname0: <type 'unicode'>
C:\Documents and Settings\└фьшэшёЄЁрЄюЁ\Desktop\testfile.txt
type of fname1: <type 'str'>
C:\Documents and Settings\Администратор\Desktop\testfile.txt
type of fname2: <type 'str'>
Traceback (most recent call last):
  File "C:\Test\getuserdir.py", line 23, in <module>
    shutil.copy(fname2,'C:\\')
  File "C:\Python25\lib\shutil.py", line 80, in copy
    copyfile(src, dst)
  File "C:\Python25\lib\shutil.py", line 46, in copyfile
    fsrc = open(src, 'rb')
IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\\x80\
xa4\xac\xa8\xad\xa8\xe1\xe2\xe0\xa0\xe2\xae\xe0\\Desktop\\testfile.txt'

3 个回答

0

问题解决了

在Windows XP系统中,桌面的路径并不是"C:\Documents and Settings\Администратор\Desktop"。正确的路径是"C:\Documents and Settings\Администратор\Рабочий стол"。这两个路径之间没有直接的对应关系。

从Windows Vista开始,你可以用"C:\users\Администратор\Desktop"来访问这个路径,但在资源管理器中,它显示的仍然是"C:\Пользователь\Администратор\Рабочий стол"。

0

作为一种解决方法,你可以使用os.chdir命令切换到那个名字里有Unicode字符的文件夹,这样shutil就不需要处理Unicode参数了。(当然,如果你的文件名里有非ASCII字符,这个方法就没用了。)

os.chdir(os.getenv("USERPROFILE")+"\\Desktop\\")
shutil.copy("testfile.txt",'C:\\')

另外,你也可以用传统的方法来复制文件。

in_file = open(os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt", "rb")
out_file = open("C:\testfile.txt", "wb")
out_file.write(in_file.read())
in_file.close()
out_file.close()

我想到的第三种解决方法是使用Python 3 :)

2

试着给 shutil.copy() 传递 Unicode 参数。也就是说,你可以这样写:shutil.copy( fname0, u'c:\\')

http://docs.python.org/howto/unicode.html#unicode-filenames

http://www.amk.ca/python/howto/unicode#unicode-filenames

http://www.python.org/dev/peps/pep-0277/

撰写回答