Python: copying files with special characters in a path

Is there a way in Python 2.5 to copy files that have special characters (Japanese characters, Cyrillic letters)? shutil.copycan't handle it.

here is a sample code:

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

output in Russian 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
source share
3 answers

os.chdir , 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

Desktop Windows XP "C:\Documents and Settings\\ ". "C:\Documents and Settings\\ ". .

Windows Vista C:\users\\Desktop, "C:\\\ " .

0

Source: https://habr.com/ru/post/1747304/


All Articles