Copy Unicode Files

it should have been a simple script

import shutil

files = os.listdir("C:\\")
for efile in files:
    shutil.copy(efile, "D:\\")

It worked fine until I tried it on a PC with files with unicode characters! python just converted these characters to question marks "????" upon receipt of the list from os.listdir, and the copying process raised an exception "file not found" !!

+3
source share
1 answer

You need to use Unicode to access file names that are not part of the ACP (ANSI) code page of the Windows system you are working on. To do this, make sure you name the directories as Unicode:

import shutil

files = os.listdir(u"C:\\")
for efile in files:
    shutil.copy(efile, u"D:\\")

Passing a Unicode string into os.listdirwill cause it to return results as Unicode strings, rather than encode them.

, os.listdir , , , - :

shutil.copy(u"C:\\" + efile, u"D:\\")

. http://docs.python.org/howto/unicode.html#unicode-filenames.

+3

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


All Articles