Python:复制带有特殊字符路径的文件

3

在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'

“shutil.copy(fname, "C:\")”会发生什么?看起来你可能对不需要编码的内容进行了编码。 - msw
IOError: [Errno 2] 没有这样的文件或目录:'C:\Documents and Settings\\x80\xa4\xac\xa8\xad\xa8\xe1\xe2\xe0\xa0\xe2\xae\xe0\Desktop\testfile.txt' - user351681
在Ubuntu Linux上,shutil.copy("Администратор/boo", "Администратор/foo")在Python 2.6中可以毫无问题地工作:/ - badp
我猜这是在Windows XP Sp3上的问题。在俄语或日语的Windows 7上,情况正常。 - user351681
3个回答

2

不,那样行不通。shutil.copy需要str参数并将其转换。 结果: IOError:[Errno 2]没有这样的文件或目录:u'C:\ Documents and Settings \\ u0410 \ u0434 \ u043c \ u0438 \ u043d \ u0438 \ u0441 \ u0442 \ u0440 \ u0430 \ u0442 \ u043e \ u0440 \ Desktop \ testfile.txt' - user351681
有趣。我手头没有Windows电脑。您用Python 2.6尝试一下方便吗?我知道在那个版本中进行了一些Unicode工作,但我不确定它是否会影响到您的问题。 - ʇsәɹoɈ
shutil 函数不修改它们的参数,而 open 函数在 Windows 上始终使用 Unicode 字符串。 - Philipp

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 :)

0

问题已解决

在Windows XP中,桌面路径不是“C:\ Documents and Settings \ Administrator \ Desktop”。它是“C:\ Documents and Settings \ Administrator \ Рабочий стол”。两者之间没有映射。

自Windows Vista以来,您可以使用C:\ users \ Administrator \ Desktop调用此路径,但在资源管理器中称为“C:\ Пользователь\ Администратор\Рабочий стол”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接