如何检查文本文件是否存在并且在python中不为空

新手上路,请多包涵

我写了一个脚本来读取 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

原文由 user3573959 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 388
1 个回答

要检查文件是否存在且不为空,您需要调用 os.path.existsos.path.getsize 的组合以及“and”条件。例如:

 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存在或您没有访问该文件的权限。例如:

 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 文档的 参考

返回路径的大小(以字节为单位)。 OSError 如果文件不存在或不可访问。

对于空文件,它将返回 0 。例如:

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

返回 True 如果路径引用现有路径或打开的文件描述符。返回 False 损坏的符号链接。

在某些平台上,此函数可能会返回 False 如果未授予在请求的文件上执行 os.stat() 的权限,即使该路径实际存在。

原文由 Moinuddin Quadri 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题