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

use*_*959 21 python filepath python-3.x

我写了一个脚本来读取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(':')
Run Code Online (Sandbox Code Playgroud)

我想检查文件是否存在而不是空文件但是这段代码给了我一个错误.

我还想检查程序是否可以写入输出文件.

命令:

python script.py -in file1.txt -out file2.txt 
Run Code Online (Sandbox Code Playgroud)

错误:

good
Traceback (most recent call last):
  File "scritp.py", line 80, in <module>
    first_cluster = clusters[0]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

Moi*_*dri 37

要检查文件是否存在且不为空,您需要调用"和"条件的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 ...
Run Code Online (Sandbox Code Playgroud)

作为替代方案,你也可以使用try/except(不使用),因为它提出 ,如果该文件不存在,或者如果你没有访问该文件的权限.例如: os.path.getsize os.path.existsOSError

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 ...
Run Code Online (Sandbox Code Playgroud)

Python 3文档中的参考资料

  • os.path.getsize() 将:

    返回路径的大小(以字节为单位).OSError如果文件不存在或无法访问,则提升.

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

    >>> import os
    >>> os.path.getsize('README.md')
    0
    
    Run Code Online (Sandbox Code Playgroud)
  • os.path.exists(path)意志是:

    返回True如果路径是指现有的路径或一个打开的文件描述符.False损坏的符号链接的返回值.

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


mar*_*her 6

在 Python3 上,您应该使用 pathlib.Path 功能来实现此目的:

import pathlib as p
path = p.Path(f)
if path.exists() and path.stat().st_size > 0:
   raise RuntimeError("file exists and is not empty")
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,Path 对象包含执行任务所需的所有功能。