2015-02-26 14 views
9

Ho scritto uno script per leggere il file di testo in python.Come verificare che il file di testo esista e non sia vuoto in python

Ecco il codice.

parser = argparse.ArgumentParser(description='script')  
parser.add_argument('-in', required=True, help='input file', 
type=argparse.FileType('r')) 
parser.add_argument('-out', required=True, help='outputfile', 
type=argparse.FileType('w'))  
args = parser.parse_args()  

try: 
    reader = csv.reader(args.in) 
    for row in reader: 
     print "good" 
except csv.Error as e: 
    sys.exit('file %s, line %d: %s' % (args.in, reader.line_num, e)) 

for ln in args.in: 
    a, b = ln.rstrip().split(':') 

Vorrei verificare se il file esiste e non è un file vuoto ma questo codice mi dà un errore.

Vorrei anche verificare se il programma può scrivere sul file di output.

Comando:

python script.py -in file1.txt -out file2.txt 

ERRORE:

good 
Traceback (most recent call last): 
    File "scritp.py", line 80, in <module> 
    first_cluster = clusters[0] 
IndexError: list index out of range 
+0

controllare questo link: http://stackoverflow.com/questions/2259382/pythonic-way-to-check-if-a-file- esiste – Vinkal

+0

che il codice non analizza nemmeno, 'in' non è un identificatore valido (in' args.in') –

+0

Dove compare 'first_cluster = cluster [0]' nel codice? –

risposta

16

Per verificare se il file è presente e non è vuoto, è necessario chiamare la combinazione di os.path.exists e os.path.getsize con la " e "condizione. Per esempio:

import os 
my_path = "/path/to/file" 

if os.path.exists(my_path) and os.path.getsize(my_path) > 0: 
    # Non empty file exists 
    # ... your code ... 
else: 
    # ... your code for else case ... 

Come alternativa, si può anche usare try/except con il os.path.getsize(senza l'utilizzo di os.path.exists) perché solleva OSError se il file non esiste, o se non hanno la permesso di accedere al file. Per esempio:

try: 
    if os.path.getsize(my_path) > 0: 
     # Non empty file exists 
     # ... your code ... 
    else: 
     # Empty file exists 
     # ... your code ... 
except OSError as e: 
    # File does not exists or is non accessible 
    # ... your code ... 

Dal documento Python 3, os.path.getsize() sarà:

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

per file vuoto, verrà restituito 0. Per esempio:

>>> import os 
>>> os.path.getsize('README.md') 
0 

mentre os.path.exists(path) volontà:

Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links.

On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

+0

risposta chiara, elegante formattazione del testo. –

Problemi correlati