7

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

How to check if a file exists in python?

Scripting in Windows

Community
  • 1
  • 1
Zygimantas
  • 33,165
  • 6
  • 21
  • 23

3 Answers3

13

This is very easy using the os module.

from os.path import exists
print exists("C:\somefile.txt")
bradley.ayers
  • 37,165
  • 14
  • 93
  • 99
  • What if the file is in an 'extended' path? Eg "\\?\C:\" – bgura May 19 '16 at 16:53
  • @bgura why would it make a difference? – Benj May 14 '19 at 12:21
  • @Benj. I actually ran into issue with long paths on windows a while back and python kept saying the path does not exist. On Windows, you need to use a special syntax to access "long" paths See this: https://stackoverflow.com/a/21194605/1161132. I cannot recall offhand if python supports the syntax or if it will normalize long path's via the conventional format (i.e. C:\path\...) – bgura May 14 '19 at 13:15
  • @bgura That's interesting! I'm afraid I cannot answer your question though... – Benj May 14 '19 at 15:24
  • This is an incorrect answer - question is about file, this will answer yes also for directories – reducing activity Jun 08 '21 at 06:38
5

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.

GaretJax
  • 7,462
  • 1
  • 38
  • 47
4

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

Amber
  • 507,862
  • 82
  • 626
  • 550