Python reading unicode folder and file names

心不动则不痛 提交于 2020-01-16 00:52:33

问题


I am new to Python. I am trying to input one path and use os.walk() to search all files, and return the files' names. I also want to use os.path.getsize() to get file size, and finally, write them into a csv file.

However, if the file name is not in English, but in Chinese, German, French, etc, Python cannot recognize it and does not return the size of the file. I'd like to use os.path.getsize(path) (referring to the example below), but it does not recognize the file's name. How can I let Python recognize the file's name and return the size of these kind of files?

For example: the file's name is: "Показатели естественного и миграционного прироста до 2030г.doc". path="C:\xxxx\xxx\xxxx\Показатели естественного и миграционного прироста до 2030г.doc"


回答1:


If you pass a Unicode input to os.walk() you will get back file-names as Unicode as well.

The following should work for you

your_base_path = u"C:\\Directory" # note this is Unicode
for root, dirs, files in os.walk(your_base_path):
    for f in files:
         print os.stat(os.path.join(root, f)).st_size


来源:https://stackoverflow.com/questions/18105873/python-reading-unicode-folder-and-file-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!