Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Copying files with special characters in path [closed]

Is there a way in Python 2.5 to copy files which have special chars (Japanese chars, cyrillic letters) in their path? shutil.copy cannot handle this.

here is some example 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:\\')

the output on a 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'
like image 837
user351681 Avatar asked Feb 01 '26 12:02

user351681


1 Answers

Try passing unicode arguments to shutil.copy(). That is, 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/

like image 81
ʇsәɹoɈ Avatar answered Feb 03 '26 00:02

ʇsәɹoɈ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!