在Python 2.7.5中使用os.path.getsize()获得文件大小 [英] Obtain File size with os.path.getsize() in Python 2.7.5

查看:146
本文介绍了在Python 2.7.5中使用os.path.getsize()获得文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手.我正在尝试使用os.path.getsize()获取文件大小.但是,如果文件名不是在Englist中,而是中文,Gemany或法文等,则Python无法识别它,并且不返回文件的大小.你能帮我吗?如何让Python识别文件名并返回此类文件的大小?

I am new to python. I am trying to use os.path.getsize() to obtain the file size. However, if the file name is not in Englist, but in Chinese, Gemany, or French, etc, Python cannot recognize it and do not return the size of the file. Could you please help me with it? How can I let Python recognize the file's name and return the size of these kind of files?

例如: 该文件的名称是:Показателиестественногоимиграционногоприростадо2030г.doc

For example: The file's name is:Показатели естественного и миграционного прироста до 2030г.doc

path ="C:\ xxxx \ xxx \ xxxx \Показателиестественногоимиграционнооприростадо2030г.doc"

path="C:\xxxx\xxx\xxxx\Показатели естественного и миграционного прироста до 2030г.doc"

我想使用" os.path.getsize(path)

I'd like to use" os.path.getsize(path)

但是它不能识别文件名.请您告诉我我该怎么办?

But it does not recognize the file name. Could you please kindly tell me what should I do?

非常感谢!

推荐答案

使用Unicode文件名,并让Python将代码点编码为系统的正确编码.

Use Unicode filenames and let Python encode the codepoints to the correct encoding for your system.

或者,自己检测文件系统编码,并确保将文件名传递给os.path.getsize()函数时,确保文件名使用该特定编码.

Alternatively, detect the filesystem encoding yourself, and ensure that your filenames are using that specific encoding when passing these to the os.path.getsize() function.

如果您尚不知道Unicode是什么,或者它与编码的关系如何,我敦促您阅读:

If you do not yet know what Unicode is, or how that relates to encodings, I urge you to read:

  • The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky

Python Unicode HOWTO

实用Unicode

继续之前.

如果要在源代码中指定文字字符串,则需要确保已指定用于保存源代码的编解码器,并使用unicode文字:

If you are specifying a literal string in your source code, then you need to make sure that you have specified the codec used to save your source, and to use a unicode literal:

# -*- coding: utf-8 -*-

path = u"C:\xxxx\xxx\xxxx\Показатели естественного и миграционного прироста до 2030г.doc"

指定您将源代码保存在UTF-8中,并且path变量应包含Unicode字符串(请注意u''字符串文字).

specifies that you saved your source code in UTF-8 and that the path variable should hold a Unicode string (note the u'' string literal).

这篇关于在Python 2.7.5中使用os.path.getsize()获得文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆