2011-07-06 16 views
286

¿Hay una función incorporada para obtener el tamaño de un objeto de archivo en bytes? Veo que algunas personas hacen algo como esto:Obtener tamaño de archivo en Python?

def getSize(fileobject): 
    fileobject.seek(0,2) # move the cursor to the end of the file 
    size = fileobject.tell() 
    return size 

file = open('myfile.bin', 'rb') 
print getSize(file) 

Pero desde mi experiencia con Python, que tiene una gran cantidad de funciones de ayuda, así que supongo que tal vez hay uno incorporado.

Respuesta

113
os.path.getsize(path) 

Devuelve el tamaño, en bytes, de la ruta. Levante os.error si el archivo no existe o no es accesible.

+0

simple y fácil :) –

411

tratar de tomar un vistazo a http://docs.python.org/library/os.path.html#os.path.getsize

os.path.getsize(path) Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.

import os 
os.path.getsize('C:\\Python27\\Lib\\genericpath.py') 

O

os.stat('C:\\Python27\\Lib\\genericpath.py').st_size 
+0

que todos ustedes Gracias. No sé si puede responder a todas las publicaciones a la vez, por lo que me limitaré al último respondedor. Parece que no puedo hacer que funcione. 'Archivo" C: \\ python \ lib \ genericpath.py ", línea 49, en getsize return os.stat (filename) .st_size TypeError: stat() argumento 1 debe ser cadena codificada sin bytes NULL, no str' –

+1

Creo que necesita "C: \\ python \\ lib \\ genericpath.py" - por ejemplo os.path.getsize ('C: \\ Python27 \\ Lib \\ genericpath.py') o os.stat ('C: \\ Python27 \\ Lib \\ genericpath.py'). st_size –

+0

@ 696, Python le permitirá tener NULL bytes, pero no tiene sentido pasarlos a getsize porque el nombre de archivo no puede tener bytes NULL. –

14

Trate

os.path.getsize(filename) 

Debe devolver el tamaño de un archivo, reportado por os.stat().

44

Es posible utilizar os.stat() función, que es un envoltorio de llamada al sistema stat():

import os 

def getSize(filename): 
    st = os.stat(filename) 
    return st.st_size 
Cuestiones relacionadas