2010-01-20 60 views
486

我正在Windows中編寫一個Python腳本。我想根據文件大小做一些事情。例如,如果大小大於0,我會發送電子郵件給某人,否則繼續其他事情。如何檢查python中的文件大小?

如何檢查文件大小?

回答

464

os.stat使用,並使用所得到的對象的st_size構件:

>>> import os 
>>> statinfo = os.stat('somefile.txt') 
>>> statinfo 
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732) 
>>> statinfo.st_size 
926L 

輸出以字節爲單位。

+13

這是在字節?或者有點? – 2012-12-11 09:11:20

+59

這是字節 – 2012-12-11 19:56:02

+24

@HaikalNashuha我知道沒有文件系統允許分數字節文件 – 2014-03-16 08:35:56

754

這樣的(信用http://www.daniweb.com/forums/thread78629.html):

>>> import os 
>>> b = os.path.getsize("/path/isa_005.mp3") 
>>> b 
2071611L 

輸出以字節爲單位。

+82

注:'執行os.path.getsize'簡直是'回報os.stat(文件名).st_size' – wim 2013-03-21 11:20:19

+172

但是,唉,怎麼更清晰比'st_size'! – 2014-01-15 03:53:28

+0

因此,使用os.path.getsize而不是os.stat(file).st_size會有一分鐘的性能損失嗎? – wordsforthewise 2015-05-18 01:45:36

93

其他的答案真正的文件工作,但如果你需要的東西,對於「類文件對象」的作品,試試這個:

# f is a file-like object. 
f.seek(0, os.SEEK_END) 
size = f.tell() 

它適用於真正的文件和StringIO的公司,在我有限的測試。 (Python 2.7.3。)當然,「類文件對象」API並不是真正的嚴格界面,但API documentation建議文件類對象應該支持seek()tell()

編輯

這和os.stat()之間的另一個區別是,你可以stat()即使你沒有權限讀取它的文件。除非您有閱讀許可,否則顯然這種尋求/告知方法將不起作用。

編輯2

在喬納森的建議,這裏是一個偏執的版本。 (以上版本離開在文件末尾的文件指針,所以如果你嘗試從文件中讀取,你會得到零個字節回來了!)

+5

您不需要導入'os',而是寫'f.seek(0,2)'從末尾查找0個字節。 – cdosborn 2015-04-03 03:58:46

+2

對於最後一行,如果沒有使用'''''''''''''''f.seek(old_file_position,0)''' – luckydonald 2015-12-02 15:11:48

+23

如果你使用整數文字而不是命名變量,那麼你正在折磨任何人必須維護你的代碼。沒有導入'os'的強制理由。 – 2015-12-02 16:25:35

31
import os 


def convert_bytes(num): 
    """ 
    this function will convert bytes to MB.... GB... etc 
    """ 
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: 
     if num < 1024.0: 
      return "%3.1f %s" % (num, x) 
     num /= 1024.0 


def file_size(file_path): 
    """ 
    this function will return the file size 
    """ 
    if os.path.isfile(file_path): 
     file_info = os.stat(file_path) 
     return convert_bytes(file_info.st_size) 


# Lets check the file size of MS Paint exe 
# or you can use any file path 
file_path = r"C:\Windows\System32\mspaint.exe" 
print file_size(file_path) 

結果:

6.1 MB 
+1

你的答案幫了我很多.. – 2017-01-17 08:06:24

+2

'這個函數會把字節轉換成MB .... GB ... etc'錯誤。此函數將字節轉換爲MiB,GiB等。請參閱[本文](https://superuser.com/a/1077275/174299)。 – moi 2017-07-18 07:30:52

9

使用pathlibadded in Python 3.4和可在PyPI)...

from pathlib import Path 
file = Path()/'doc.txt' # or Path('./doc.txt') 
size = file.stat().st_size 

這實際上只是一個圍繞os.stat的界面,但使用pathlib提供了一種訪問其他文件相關操作的簡單方法。

3

嚴格執行的問題,Python代碼(+僞代碼)將是:

import os 
file_path = r"<path to your file>" 
if os.stat(file_path).st_size > 0: 
    <send an email to somebody> 
else: 
    <continue to other things> 
3

有一個bitshift招我用,如果我想從bytes轉換爲其他任何單位。如果您通過10進行右移,您基本上會將其移動一個訂單(多個)。

例子:5GB are 5368709120 bytes

print (5368709120 >> 10) # 5242880 kilo Bytes (kB) 
print (5368709120 >> 20) # 5120 Mega Bytes(MB) 
print (5368709120 >> 30) # 5 Giga Bytes(GB)