Quantcast
Channel: How do I check whether a file exists without exceptions? - Stack Overflow
Browsing latest articles
Browse All 46 View Live

Answer by masterofallthings for How do I check whether a file exists without...

Another possible option is to check whether the filename is in the directory using os.listdir()import osif 'foo.txt' in os.listdir(): # Do thingsthis will return true if it is and false if not

View Article



Answer by Memin for How do I check whether a file exists without exceptions?

TL;DRanswer is: pathlib modulePathlib is probably the most modern and convenient way for almost all of the file operations. For the existence of a file or a folder a single line of code is enough.from...

View Article

Answer by Devbrat Shukla for How do I check whether a file exists without...

Use os.path.exists() to check whether file exists or not:def fileAtLocation(filename,path): return os.path.exists(path + filename)filename="dummy.txt"path =...

View Article

Answer by Gopinath for How do I check whether a file exists without exceptions?

exists() and is_file() methods of 'Path' object can be used for checking if a given path exists and is a file.Python 3 program to check if a file exists:# File name: check-if-file-exists.pyfrom pathlib...

View Article

Answer by Vimal Maheedharan for How do I check whether a file exists without...

import os# for testing purpose args defaulted to current folder & file. # returns True if file founddef file_exists(FOLDER_PATH='../', FILE_NAME=__file__): return os.path.isdir(FOLDER_PATH) \ and...

View Article


Answer by Ali Hallaji for How do I check whether a file exists without...

Check file or directory existsYou can follow these three ways:Note1: The os.path.isfile used only for filesimport os.pathos.path.isfile(filename) # True if file existsos.path.isfile(dirname) # False if...

View Article

Answer by AbstProcDo for How do I check whether a file exists without...

Date:2017-12-04Every possible solution has been listed in other answers.An intuitive and arguable way to check if a file exists is the following:import osos.path.isfile('~/file.md') # Returns True if...

View Article

Answer by durjoy for How do I check whether a file exists without exceptions?

If you imported NumPy already for other purposes then there is no need to import other libraries like pathlib, os, paths, etc.import numpy as npnp.DataSource().exists("path/to/your/file")This will...

View Article


Answer by CristiFati for How do I check whether a file exists without...

Although almost every possible way has been listed in (at least one of) the existing answers (e.g. Python 3.4 specific stuff was added), I'll try to group everything together.Note: every piece of...

View Article


Answer by Inconnu for How do I check whether a file exists without exceptions?

How do I check whether a file exists, without using the try statement?In 2016, this is still arguably the easiest way to check if both a file exists and if it is a file:import...

View Article

Image may be NSFW.
Clik here to view.

Answer by Tom Fuller for How do I check whether a file exists without...

Testing for files and folders with os.path.isfile(), os.path.isdir() and os.path.exists()Assuming that the "path" is a valid path, this table shows what is returned by each function for files and...

View Article

Answer by Marcel Wilson for How do I check whether a file exists without...

Adding one more slight variation which isn't exactly reflected in the other answers.This will handle the case of the file_path being None or empty string.def file_exists(file_path): if not file_path:...

View Article

Answer by iPhynx for How do I check whether a file exists without exceptions?

You can use os.listdir to check if a file is in a certain directory.import osif 'file.ext' in os.listdir('dirpath'): #code

View Article


Answer by Mike McKerns for How do I check whether a file exists without...

I'm the author of a package that's been around for about 10 years, and it has a function that addresses this question directly. Basically, if you are on a non-Windows system, it uses Popen to access...

View Article

Answer by KaiBuxe for How do I check whether a file exists without exceptions?

In 2016 the best way is still using os.path.isfile:>>> os.path.isfile('/path/to/some/file.txt')Or in Python 3 you can use pathlib:import pathlibpath = pathlib.Path('/path/to/some/file.txt')if...

View Article


Answer by Love and peace - Joe Codeswell for How do I check whether a file...

Here's a 1 line Python command for the Linux command line environment. I find this VERY HANDY since I'm not such a hot Bash guy.python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"I...

View Article

Answer by Aaron Hall for How do I check whether a file exists without...

How do I check whether a file exists, using Python, without using a try statement?Now available since Python 3.4, import and instantiate a Path object with the file name, and check the is_file method...

View Article


Answer by Khaled.K for How do I check whether a file exists without exceptions?

import os.pathdef isReadableFile(file_path, file_name): full_path = file_path +"/"+ file_name try: if not os.path.exists(file_path): print "File path is invalid." return False elif not...

View Article

Answer by codelox for How do I check whether a file exists without exceptions?

import os#Your path here e.g. "C:\Program Files\text.txt"#For access purposes: "C:\\Program Files\\text.txt"if os.path.exists("C:\..."): print "File found!"else: print "File not found!"Importing os...

View Article

Answer by Pedro Lobito for How do I check whether a file exists without...

if os.path.isfile(path_to_file): try: open(path_to_file) pass except IOError as e: print "Unable to open file"Raising exceptions is considered to be an acceptable, and Pythonic, approach for flow...

View Article

Answer by Zizouz212 for How do I check whether a file exists without exceptions?

Although I always recommend using try and except statements, here are a few possibilities for you (my personal favourite is using os.access):Try opening the file:Opening the file will always verify the...

View Article


Answer by Pradip Das for How do I check whether a file exists without...

You can use the "OS" library of Python:>>> import os>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt") True>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")False

View Article


Answer by Hanson for How do I check whether a file exists without exceptions?

To check if a file exists, from sys import argvfrom os.path import existsscript, filename = argvtarget = open(filename)print "file exists: %r" % exists(filename)

View Article

Answer by bergercookie for How do I check whether a file exists without...

If the file is for opening you could use one of the following techniques:with open('somefile', 'xt') as f: #Using the x-flag, Python3.3 and above f.write('Hello\n')if not os.path.exists('somefile'):...

View Article

Answer by Zaheer for How do I check whether a file exists without exceptions?

You can use the following open method to check if a file exists + readable:file = open(inputFile, 'r')file.close()

View Article


Answer by Chris for How do I check whether a file exists without exceptions?

You can write Brian's suggestion without the try:.from contextlib import suppresswith suppress(IOError), open('filename'): process()suppress is part of Python 3.4. In older releases you can quickly...

View Article

Answer by Cody Piersall for How do I check whether a file exists without...

Python 3.4+ has an object-oriented path module: pathlib. Using this new module, you can check whether a file exists like this:import pathlibp = pathlib.Path('path/to/file')if p.is_file(): # or...

View Article

Answer by chad for How do I check whether a file exists without exceptions?

It doesn't seem like there's a meaningful functional difference between try/except and isfile(), so you should use which one makes sense.If you want to read a file, if it exists, dotry: f =...

View Article

Answer by un33k for How do I check whether a file exists without exceptions?

This is the simplest way to check if a file exists. Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it.import osfname = "foo.txt"if...

View Article



Answer by Yugal Jindle for How do I check whether a file exists without...

Use os.path.isfile() with os.access():import osPATH = './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...

View Article

Answer by Jesvin Jose for How do I check whether a file exists without...

import ospath = /path/to/dirroot,dirs,files = os.walk(path).next()if myfile in files: print "yes it exists"This is helpful when checking for several files. Or you want to do a set intersection/...

View Article

Answer by philberndt for How do I check whether a file exists without...

You could try this (safer):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:...

View Article

Answer by pkoch for How do I check whether a file exists without exceptions?

Prefer the try statement. It's considered better style and avoids race conditions.Don't take my word for it. There's plenty of support for this theory. Here's a couple:Style: Section "Handling unusual...

View Article


Answer by bortzmeyer for How do I check whether a file exists without...

Unlike isfile(), exists() will return True for directories. So depending on if you want only plain files or also directories, you'll use isfile() or exists(). Here is some simple REPL...

View Article

Answer by zgoda for How do I check whether a file exists without exceptions?

Additionally, os.access():if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read()Being R_OK, W_OK, and X_OK the flags to test for permissions (doc).

View Article

Answer by rslite for How do I check whether a file exists without exceptions?

If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or...

View Article


Answer by PierreBdR for How do I check whether a file exists without exceptions?

You have the os.path.exists function:import os.pathos.path.exists(file_path)This returns True for both files and directories but you can instead useos.path.isfile(file_path)to test if it's a file...

View Article


Answer by benefactual for How do I check whether a file exists without...

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

View Article

Answer by Paul for How do I check whether a file exists without exceptions?

import os.pathif os.path.isfile(filepath): print("File exists")

View Article

How do I check whether a file exists without exceptions?

How do I check whether a file exists or not, without using the try statement?

View Article

Answer by Ban_Midou for How do I check whether a file exists without exceptions?

This is how i found a list of files(in this images) in one folder and searched it in a folder (with subfolders)# This script concatenates javascript files into a unified js to reduce server...

View Article

Browsing latest articles
Browse All 46 View Live




Latest Images