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

标签 python file copy shutil

<分区>

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'

最佳答案

关于Python:复制路径中带有特殊字符的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2919205/

相关文章:

python:查找 cdf 的随机变量的值

Java 文件 IO 异常

c++ - 如何使用 program.exe < text.txt 使用 C++ 读取输入

c# - 如何在FTP服务器上复制文件?

python - 试图让 Anaconda3 在 Mac 上运行

python - Python 列表中的交替方向 - 更多 Pythonic 解决方案

c++ - 数组对象初始化,其类具有一些 ctor/dtor

c# - 在 C# 中将列的子集从一个 datagridview 复制到新的 datagridview

python - CPLEX 的 Python 中的 Bender 分解示例

file - Go connection.Writer 和 reader 行为不正常,在一次读取操作中读取 2 写入