2010-03-24 15 views

Respuesta

176
>>> import os 
>>> os.stat("file").st_size == 0 
True 
+9

'stat.ST_SIZE' en lugar de 6 – wRAR

+1

eso está bien también. pero no quiero importar estadísticas. Su corta y lo suficientemente dulce y la posición de tamaño en la lista devuelta no va a cambiar pronto. – ghostdog74

+48

@wRAR: os.stat ('file'). St_size es incluso mejor –

87
import os  
os.path.getsize(fullpathhere) > 0 
+6

Por razones de seguridad puede que tenga que coger 'OSError' y devolver Falso. – kennytm

+3

¿Cuál es la diferencia/ventaja al usar este vs os.state ('file'). St_size? –

+0

Parece que los dos son iguales bajo el capó: https://stackoverflow.com/a/18962257/1397061 –

16

si por alguna razón que ya tenían el archivo abierto puede probar esto:

>>> with open('New Text Document.txt') as my_file: 
...  # I already have file open at this point.. now what? 
...  my_file.seek(0) #ensure you're at the start of the file.. 
...  first_char = my_file.read(1) #get the first character 
...  if not first_char: 
...   print "file is empty" #first character is the empty string.. 
...  else: 
...   my_file.seek(0) #first character wasn't empty, return to start of file. 
...   #use file now 
... 
file is empty 
54

Tanto getsize() y stat() será una excepción si no existe el archivo. Esta función devolverá verdadero/falso sin tirar:

import os 
def is_non_zero_file(fpath): 
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0 
+0

Definitivamente como usar '' os.path.getsize() '' –

+3

Hay una condición de carrera porque el archivo puede estar eliminado entre las llamadas a 'os.path.isfile (fpath)' y 'os.path.getsize (fpath)', en cuyo caso la función propuesta generará una excepción. – s3rvac

+1

Mejor intentar y atrapar el 'OSError' en su lugar, como propuesto [en otro comentario] (http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not/15924160# comment2503155_2507819). – j08lue

6

Ok así que voy a combinar ghostdog74's answer y los comentarios, sólo por diversión.

>>> import os 
>>> os.stat('c:/pagefile.sys').st_size==0 
False 

False significa un archivo no vacío.

Así que vamos a escribir una función:

import os 

def file_is_empty(path): 
    return os.stat(path).st_size==0 
Cuestiones relacionadas