import osos.path.exists(path) # Returns whether the path (directory or file) exists or notos.path.isfile(path) # Returns whether the file exists or not
try:# http://effbot.org/zone/python-with-statement.htm# 'with' is safer to open a filewith open('whatever.txt') as fh:# Do something with 'fh'except IOError as e:print("({})".format(e))
import os
PATH = './file.txt'if os.path.isfile(PATH) and os.access(PATH, os.R_OK):print("File exists and is readable")else:print("Either the file is missing or not readable")
with open('somefile', 'xt') as f: # Using the x-flag, Python 3.3 and abovef.write('Hello\n')
if not os.path.exists('somefile'):with open('somefile', 'wt') as f:f.write("Hello\n")else:print('File already exists!')
This will check whether you have access to the file. It will check for permissions. Based on the os.py documentation, typing in os.F_OK, it will check the existence of the path. However, using this will create a security hole, as someone can attack your file using the time between checking the permissions and opening the file. You should instead go directly to opening the file instead of checking its permissions. (EAFP vs LBYP). If you're not going to open the file afterwards, and only checking its existence, then you can use this.
I should also mention that there are two ways that you will not be able to verify the existence of a file. Either the issue will be permission denied or no such file or directory. If you catch an IOError, set the IOError as e (like my first option), and then type in print(e.args) so that you can hopefully determine your issue. I hope it helps! :)
def is_file(self):"""Whether this path is a regular file (also True for symlinks pointingto regular files)."""try:return S_ISREG(self.stat().st_mode)except OSError as e:if e.errno not in (ENOENT, ENOTDIR):raise# Path doesn't exist or is a broken symlink# (see https://bitbucket.org/pitrou/pathlib/issue/12/)return False
from contextlib import suppressfrom pathlib import Path
用法:
>>> with suppress(OSError), Path('doesnotexist').open() as f:... for line in f:... print(line)...>>>>>> with suppress(OSError):... Path('doesnotexist').unlink()...>>>
# This follows symbolic links, so both islink() and isdir() can be true# for the same path on systems that support symlinksdef isfile(path):"""Test whether a path is a regular file"""try:st = os.stat(path)except os.error:return Falsereturn stat.S_ISREG(st.st_mode)
>>> print pox.find.__doc__find(patterns[,root,recurse,type]); Get path to a file or directory
patterns: name or partial name string of items to search forroot: path string of top-level directory to searchrecurse: if True, recurse down from root directorytype: item filter; one of {None, file, dir, link, socket, block, char}verbose: if True, be a little verbose about the search
On some OS, recursion can be specified by recursion depth (an integer).patterns can be specified with basic pattern matching. Additionally,multiple patterns can be specified by splitting patterns with a ';'For example:>>> find('pox*', root='..')['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']
>>> find('*shutils*;*init*')['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']
>>>
>>> import os>>> path = "path to a word document">>> os.path.isfile(path)True>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docxTrue
def is_file(self):"""Whether this path is a regular file (also True for symlinks pointingto regular files)."""try:return S_ISREG(self.stat().st_mode)except OSError as e:if e.errno not in (ENOENT, ENOTDIR):raise# Path doesn't exist or is a broken symlink# (see https://bitbucket.org/pitrou/pathlib/issue/12/)return False
class Swallow: # Dummy exampleswallowed_exceptions = (FileNotFoundError,)
def __enter__(self):print("Entering...")
def __exit__(self, exc_type, exc_value, exc_traceback):print("Exiting:", exc_type, exc_value, exc_traceback)return exc_type in Swallow.swallowed_exceptions # only swallow FileNotFoundError (not e.g. TypeError - if the user passes a wrong argument like None or float or ...)
import os
os.path.isfile('~/file.md') # Returns True if exists, else False
# Additionally, check a directoryos.path.isdir('~/folder') # Returns True if the folder exists, else False
# Check either a directory or a fileos.path.exists('~/file')
import os
# For testing purposes the arguments defaulted to the current folder and file.# returns True if file founddef file_exists(FOLDER_PATH='../', FILE_NAME=__file__):return os.path.isdir(FOLDER_PATH) \and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))
# File name: check-if-file-exists.py
from pathlib import Path
filePath = Path(input("Enter path of the file to be found: "))
if filePath.exists() and filePath.is_file():print("Success: File exists")else:print("Error: File does not exist")
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..')
# This script concatenates JavaScript files into a unified JavaScript file to reduce server round-trips
import osimport stringimport mathimport ntpathimport sys
#import pyodbc
import gzipimport shutil
import hashlib
# BUF_SIZE is totally arbitrary, change for your app!BUF_SIZE = 65536 # Let’s read stuff in 64 kilobyte chunks
# Iterate over all JavaScript files in the folder and combine themfilenames = []shortfilenames = []
imgfilenames = []imgshortfilenames = []
# Get a unified path so we can stop dancing with user paths.# Determine where files are on this machine (%TEMP% directory and application installation directory)if '.exe' in sys.argv[0]: # if getattr(sys, 'frozen', False):RootPath = os.path.abspath(os.path.join(__file__, "..\\"))
elif __file__:RootPath = os.path.abspath(os.path.join(__file__, "..\\"))
print ("\n storage of image files RootPath: %s\n" %RootPath)
FolderPath = "D:\\TFS-FARM1\\StoneSoup_STS\\SDLC\\Build\\Code\\StoneSoup_Refactor\\StoneSoupUI\\Images"print ("\n storage of image files in folder to search: %s\n" %FolderPath)
for root, directories, filenames2 in os.walk(FolderPath):for filename in filenames2:fullname = os.path.join(root, filename)filenames.append(fullname)shortfilenames.append(filename)
for i, fname in enumerate(shortfilenames):print("%s - %s" % (i+1, fname))
for root, directories, filenames2 in os.walk(RootPath):for filename in filenames2:fullname = os.path.join(root, filename)imgfilenames.append(fullname)imgshortfilenames.append(filename)
for i, fname in enumerate(imgshortfilenames):print("%s - %s" % (i+1, fname))
for i, fname in enumerate(imgshortfilenames):if fname in shortfilenames:print("%s - %s exists" % (i+1, fname))else:print("%s - %s ABSENT" % (i+1, fname))