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". ;-) Commented Aug 2, 2011 at 6:25
  • Note that selected answer is incorrect - question is about file, selected asnwer will respond "yes" also for directories Commented 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")
Sign up to request clarification or add additional context in comments.

5 Comments

What if the file is in an 'extended' path? Eg "\\?\C:\<very long path>"
@bgura why would it make a difference?
@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 That's interesting! I'm afraid I cannot answer your question though...
This is an incorrect answer - question is about file, this will answer yes also for directories
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 Comment

This is an incorrect answer - question is about file, this will answer yes also for directories
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 Comment

Could you please summarise those links?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.