我写了一个脚本来读取python中的文本文件。
这里是代码。
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(':')
我想检查文件是否存在并且不是空文件,但是这段代码给了我一个错误。
我还想检查程序是否可以写入输出文件。
命令:
python script.py -in file1.txt -out file2.txt
错误:
good
Traceback (most recent call last):
File "scritp.py", line 80, in <module>
first_cluster = clusters[0]
IndexError: list index out of range
最佳答案
要检查文件是否存在且不为空,需要调用os.path.exists
的组合和 os.path.getsize
与“和”条件。例如:
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 ...
作为替代方法,您也可以将 try/except
与 os.path.getsize
一起使用(不使用 os.path.exists
) 因为它会引发
OSError
如果该文件不存在或者您没有访问该文件的权限。例如:
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 文档
-
Return the size, in bytes, of path. Raise
OSError
if the file does not exist or is inaccessible.对于空文件,它会返回
0
。例如:>>> import os >>> os.path.getsize('README.md') 0
-
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.
关于python - 如何检查文本文件是否存在并且在python中不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28737292/