8

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

How to check if a file exists in python?

Scripting in Windows

2
  • @vpit3833: I would say "more than possibly". ;-)
    – GaretJax
    Aug 2, 2011 at 6:25
  • Note that selected answer is incorrect - question is about file, selected asnwer will respond "yes" also for directories Jun 8, 2021 at 6:39

3 Answers 3

13

This is very easy using the os module.

from os.path import exists
print exists("C:\somefile.txt")
5
  • What if the file is in an 'extended' path? Eg "\\?\C:\<very long path>"
    – bgura
    May 19, 2016 at 16:53
  • @bgura why would it make a difference?
    – Benj
    May 14, 2019 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: 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, 2019 at 13:15
  • @bgura That's interesting! I'm afraid I cannot answer your question though...
    – Benj
    May 14, 2019 at 15:24
  • This is an incorrect answer - question is about file, this will answer yes also for directories Jun 8, 2021 at 6: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.

1
  • This is an incorrect answer - question is about file, this will answer yes also for directories Jun 8, 2021 at 6:38
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

1
  • Could you please summarise those links?
    – Benj
    May 17, 2019 at 8:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.