Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file exists in python? [duplicate]

Possible Duplicate:
Pythonic way to check if a file exists?

How to check if a file exists in python?

Scripting in Windows

like image 320
Zygimantas Avatar asked Aug 02 '11 06:08

Zygimantas


People also ask

How do you check if a file already exists in Python?

isfile() Method to check if file exists. os. path. isfile() method in Python is used to check whether the specified path is an existing regular file or not.

How do you check whether a file exists in a directory in Python?

We use the is_file() function, which is part of the Path class from the pathlib module, or exists() function, which is part of the os. path module, in order to check if a file exists or not in Python.

How do I check to see if a file exists?

To check if a file exists, you pass the file path to the exists() function from the os.path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .


3 Answers

This is very easy using the os module.

from os.path import exists
print exists("C:\somefile.txt")
like image 80
bradley.ayers Avatar answered Oct 16 '22 23:10

bradley.ayers


Check the manual, this is a really easy question:

http://docs.python.org/library/os.path.html#os.path.exists

os.path.exists(path)

Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

like image 23
GaretJax Avatar answered Oct 17 '22 01:10

GaretJax


http://docs.python.org/library/os.path.html#os.path.exists

or if you want to also ensure that said path is actually a file (as opposed to a directory, link, etc):

http://docs.python.org/library/os.path.html#os.path.isfile

like image 41
Amber Avatar answered Oct 17 '22 00:10

Amber