Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check text file exists and is not empty in python

I wrote a script to read text file in python.

Here is the code.

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(':') 

I would like to check if the file exists and is not empty file but this code gives me an error.

I would also like to check if program can write to output file.

Command:

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

ERROR:

good Traceback (most recent call last):   File "scritp.py", line 80, in <module>     first_cluster = clusters[0] IndexError: list index out of range 
like image 572
user3573959 Avatar asked Feb 26 '15 08:02

user3573959


People also ask

How do I know if a text file is empty Python?

txt is empty if os. path. getsize('nodata. txt') == 0: print("File is empty!")

How can u find out whether the file is empty or not?

Check if the File is Empty using os.getsize() to check whether a file is empty or not. It takes the file path as an argument. It will check for the file size. If the file size is 0, it will print the file as Empty.


1 Answers

To check whether file is present and is not empty, you need to call the combination of os.path.exists and os.path.getsize with the "and" condition. For example:

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 ... 

As an alternative, you may also use try/except with the os.path.getsize (without using os.path.exists) because it raises OSError if the file does not exist or if you do not have the permission to access the file. For example:

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 ... 

References from the Python 3 document

  • os.path.getsize() will:

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

    For empty file, it will return 0. For example:

    >>> import os >>> os.path.getsize('README.md') 0 
  • whereas os.path.exists(path) will:

    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.

like image 151
Moinuddin Quadri Avatar answered Sep 29 '22 13:09

Moinuddin Quadri