-3

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

Im new to programming so bear with me.

Im wondering, how would you know if a file exists in python?

for example. ~/file.txt

Instead of a directory,the actual file itself within my directory? returning a True statement if the "file.txt" exists?

Thanks everyone.

Community
  • 1
  • 1
  • 1
    It's worth mentioning that most of the time people ask for this, it's not actually what they want. If you're planning to check for existence before opening the file, don't do that—just open the file and deal with an exception if it was missing. It's more Pythonic, and it also avoids a race condition that's been used to exploit Unix systems for decades. – abarnert Sep 24 '12 at 17:23

3 Answers3

2

Check out exists() and isfile() functions of os.path module..

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

The os.path module is your friend:

import os

os.path.exists(filename)

Also see os.path.isfile() to test if a given file is a regular file versus a directory.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Look into os.path.exists. Of course, that doesn't work for ~/file since ~ is expanded by your shell. For that, there exists os.path.expanduser

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Thanks everyone. but when i import my module os. and state os.path.exists or os.path.isfile it dosn't exist? im sorry guys im a complete noob on this im trying my best to learn everything. – enjoipython Sep 24 '12 at 17:15