Python文件名问题

2024-03-29 14:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找到一个使用操作系统列表目录()函数(或任何其他方法),并返回该目录中的所有文件名,但将非ASCII字符转换为unicode格式。例如,如果我有文件Hello WorlЪ.py,我希望函数返回Hello Worl\u042a.py或类似的内容。感谢您的帮助。你知道吗


Tags: 文件方法函数py目录内容hello列表
2条回答

str.encode("unicode_escape")将按照您描述的方式对字符串进行编码。你知道吗

>>> print(u"Hello WorlЪ.py".encode("unicode_escape"))
Hello Worl\u042a.py

如果传递os.listdirunicode路径,则os.listdir返回unicode:

os.listdir(u'.')

the docs

Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. Undecodable filenames will still be returned as string objects.

相关问题 更多 >