import os import shutil def touch(name): open(name, 'wb').close() unicode_dirname = "test" dirname = os.fsencode(unicode_dirname) os.mkdir(dirname) try: touch(os.path.join(dirname, b'ascii.txt')) touch(os.path.join(dirname, 'latin1:\xe9.txt'.encode('latin1'))) touch(os.path.join(dirname, 'utf8:\xe9\u20ac.txt'.encode('utf8'))) touch(os.path.join(dirname, b'invalid_utf8:\xff.txt')) for name in sorted(os.listdir(unicode_dirname)): try: print(name) except UnicodeEncodeError: print("" % name) finally: shutil.rmtree(dirname)