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

标签 python python-3.x filepath

我写了一个脚本来读取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/exceptos.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 文档

  • os.path.getsize()将:

    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
    
  • os.path.exists(path)将:

    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.

关于python - 如何检查文本文件是否存在并且在python中不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28737292/

相关文章:

java - 连接字符串中的绝对文件路径

file - 使用动态文件名保存 pandas excel 数据框

python - 具有空值的 Django 网址

python - 如何在Python中从shell中获取变量?

python-3.x - SQLalchemy,为什么flask 设置Base.query?

python - 从 __init__ 调用类方法而不重复类名

包含文件的PHP文件路径

python - python 服务器包装器的示例代码

Python:自 1970.01.01 GMT 午夜到任意时间 GMT 的秒数?

python - 是否可以将 .exe 文件转换为 .py?