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

2024-05-20 02:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

Python2.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'

Tags: andoftxttypefnamedocumentsprintcopy
3条回答

作为解决方法,可以^{}到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:)

解决了这个问题

Windows XP中的桌面路径不是“C:\文档和设置”。它是“C:文件和设置”。现在两者之间有了映射。

由于Windows Vista,您可以使用“桌面”调用此路径,但在资源管理器中,它被称为“C:”,“C:”,“用户”。

相关问题 更多 >