【问题标题】:How to check text file exists and is not empty in python如何检查文本文件是否存在并且在python中不为空
【发布时间】:2015-04-28 12:36:37
【问题描述】:

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

【问题讨论】:

  • 该代码甚至无法解析,in 不是有效标识符(在args.in 中)
  • first_cluster = clusters[0] 出现在您的代码中的什么位置?
  • 脚本出错,因为 FOR 循环失败。当它开始读取文件时,它无法从 args.in 读取文件。如何使用参数解析器读取文件?

标签: python python-3.x filepath


【解决方案1】:
def exist_and_not_empty(filepath):
    try:
        import pathlib as p
        path = p.Path(filepath)
        if '~' in filepath:
            path = path.expanduser()
        if not path.exists() and path.stat().st_size > 0:
            return False
        return True
    except FileNotFoundError:
        return False

这利用了上述所有建议,并解决了丢失文件的问题,并在检测到时自动扩展波浪号,因此它可以正常工作。

【讨论】:

    【解决方案2】:

    在 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")
    

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

    【讨论】:

      【解决方案3】:

      你可能想试试这个:

      def existandnotempty(fp):
          if not os.path.isfile(fp):
              retun False
          k=0
          with open(fp,'r') as f:
              for l in f:
                k+=len(l)
                if k:
                   return False
                k+=1
          return True 
      

      【讨论】:

      • 您可以随意修改。例如,如果您不希望制表符、空格等被视为“某事”,则可以使用“trim()”。如果想将只有空行的文件计为“空”,您也可以删除 k+=1 。在这种形式中,任何字符(甚至只是一个 CR)都会将您的文件标记为非空。
      【解决方案4】:

      要检查文件是否存在且不为空,您需要使用“and”条件调用os.path.existsos.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() 将:

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

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

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

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

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

      【讨论】:

      • 我用它来检查我是否必须下载一个文件:must_be_downloaded = not os.path.isfile(file_path) or os.path.getsize(file_path) == 0,它在 python 3.6 中无需 try/catch 即可工作。或者使用相反的方法:exists_for_real = os.path.isfile(file_path) and os.path.getsize(file_path) &gt; 0 你可以自己检查并添加更多条件,但我只是编写了相同的脚本,这个简单的检查在我的情况下效果很好。
      猜你喜欢
      • 2010-11-25
      • 2019-05-09
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多