Hadi
Hadi

Reputation: 727

Copying files with unicode names

this was supposed to be 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 named with unicode characters! python just converted these characters into question marks "????" when getting the list from os.listdir, and the copy process raised "file not found" exception!!

Upvotes: 3

Views: 2051

Answers (1)

Glenn Maynard
Glenn Maynard

Reputation: 57474

You need to use Unicode to access filenames which aren't in the ACP (ANSI codepage) of the Windows system you're running on. To do that, make sure you name directories as Unicode:

import shutil

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

Passing a Unicode string to os.listdir will make it return results as Unicode strings rather than encoding them.

Don't forget that os.listdir won't include path, so you probably actually want something like:

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

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

Upvotes: 3

Related Questions