如何检查是否存在文件,而不使用试用声明?


当前回答

如果您已经进口了NumPy用于其他用途,那么不需要进口其他图书馆,如Pathlib,OS,路径等。

import numpy as np
np.DataSource().exists("path/to/your/file")

这将根据它的存在返回真实或虚假。

其他回答

您可以使用以下开放方法检查是否存在 + 可阅读的文件:

file = open(inputFile, 'r')
file.close()

如果文件是要打开的,您可以使用以下技术之一:

with open('somefile', 'xt') as f: # Using the x-flag, Python 3.3 and above
    f.write('Hello\n')

if not os.path.exists('somefile'): 
    with open('somefile', 'wt') as f:
        f.write("Hello\n")
else:
    print('File already exists!')

注意:此查找一个文件或指定的名称的目录。

日期: 2017-12-04

每個可能的解決方案都被列入其他答案中。

一个直观和可争议的方式来检查是否存在文件是如下:

import os

os.path.isfile('~/file.md')  # Returns True if exists, else False

# Additionally, check a directory
os.path.isdir('~/folder')  # Returns True if the folder exists, else False

# Check either a directory or a file
os.path.exists('~/file')

我为您的参考做了一个完整的骗局:

# os.path methods in exhaustive cheat sheet
{'definition': ['dirname',
               'basename',
               'abspath',
               'relpath',
               'commonpath',
               'normpath',
               'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
               'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
              'isfile',
              'exists',
              'lexists'
              'islink',
              'isabs',
              'ismount',],
 'expand': ['expanduser',
            'expandvars'],
 'stat': ['getatime', 'getctime', 'getmtime',
          'getsize']}

你可以尝试一下(更安全):

try:
    # http://effbot.org/zone/python-with-statement.htm
    # 'with' is safer to open a file
    with open('whatever.txt') as fh:
        # Do something with 'fh'
except IOError as e:
    print("({})".format(e))

奥普特将是:

(没有此类文件或目录:‘whatever.txt’)

然后,取决于结果,你的程序可以只是从那里继续运行,或者你可以编码阻止它,如果你愿意。

使用 os.path.exists() 查看是否存在文件:

def fileAtLocation(filename,path):
    return os.path.exists(path + filename)
 

filename="dummy.txt"
path = "/home/ie/SachinSaga/scripts/subscription_unit_reader_file/"


if fileAtLocation(filename,path):
   print('file found at location..')
else:
   print('file not found at location..')