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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28737292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:40:20  来源:igfitidea点击:

How to check text file exists and is not empty in python

pythonpython-3.xfilepath

提问by user3573959

I wrote a script to read text file in python.

我写了一个脚本来读取python中的文本文件。

Here is the code.

这是代码。

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(':')

I would like to check if the file exists and is not empty file but this code gives me an error.

我想检查文件是否存在并且不是空文件,但是这段代码给了我一个错误。

I would also like to check if program can write to output file.

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

Command:

命令:

python script.py -in file1.txt -out file2.txt 

ERROR:

错误:

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

回答by Moinuddin Quadri

To check whether file is present and is not empty, you need to call the combination of os.path.existsand os.path.getsizewith the "and" condition. For example:

要检查文件是否存在且不为空,您需要使用“and”条件调用os.path.existsand的组合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 ...

As an alternative, you may also use try/exceptwith the os.path.getsize(without using os.path.exists)because it raises OSErrorif the file does not exist or if you do not have the permission to access the file. For example:

作为替代,您也可以使用try/exceptwith (不使用),因为如果文件不存在或者您没有访问文件的权限,它会引发 。例如: os.path.getsizeos.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 ...


Referencesfrom the Python 3 document

来自 Python 3 文档的参考

  • os.path.getsize()will:

    Return the size, in bytes, of path. Raise OSErrorif the file does not exist or is inaccessible.

    For empty file, it will return 0. For example:

    >>> import os
    >>> os.path.getsize('README.md')
    0
    
  • whereas os.path.exists(path)will:

    Return Trueif path refers to an existing path or an open file descriptor. Returns Falsefor broken symbolic links.

    On some platforms, this function may return Falseif permission is not granted to execute os.stat()on the requested file, even if the path physically exists.

  • os.path.getsize()将要:

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

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

    >>> import os
    >>> os.path.getsize('README.md')
    0
    
  • os.path.exists(path)将:

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

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