How to check text file exists and is not empty in python
我编写了一个脚本来读取Python中的文本文件。
这是密码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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(':') |
我想检查文件是否存在并且不是空文件,但是这个代码给出了一个错误。
我还想检查程序是否可以写入输出文件。
命令:
1 | python script.py -in file1.txt -out file2.txt |
错误:
1 2 3 4 5 | good Traceback (most recent call last): File"scritp.py", line 80, in <module> first_cluster = clusters[0] IndexError: list index out of range |
要检查文件是否存在且不为空,需要调用
1 2 3 4 5 6 7 8 | 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 ... |
作为替代方案,您也可以将
1 2 3 4 5 6 7 8 9 10 | 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 ... |
python 3文档中的引用
os.path.getsize() 将:
Return the size, in bytes, of path. Raise
OSError if the file does not exist or is inaccessible.对于空文件,返回
0 。例如:1
2
3>>> import os
>>> os.path.getsize('README.md')
0鉴于
os.path.exists(path) 将:
Return
True if path refers to an existing path or an open file descriptor. ReturnsFalse for broken symbolic links.On some platforms, this function may return
False if permission is not granted to executeos.stat() on the requested file, even if the path physically exists.