Discussion:
[Tutor] How best to determine if a db exists before trying to open it? [Was: try and file existence]
boB Stepp
2015-08-15 23:24:12 UTC
Permalink
Behalf Of Laura Creighton
[..]
I understand your points, but wonder then what is the intended use for
os.path.exists()? That is, in what types of circumstances would it be
both appropriate and safe to use?
If you want to locate dangling symlinks, os.path.exists will return
False, so
the symlink is there, but the file it pointed to is long gone.
Can't you do that with os.path.open() and get a value in os.path.status?
(I
think that is the thing to call)
Open does more that os.stat (which is what os.path.exists uses underneath).
There are plenty of times you will want to know a file exists but not have
permission to open it. Also, open can have side effects if the target file
is a device or a socket/pipe.
Always use the smallest thing you can to achieve an effect: stat is smaller
than open.
I actually had a specific example in mind when I asked my question.
My current project will require me to create and then use an SQLite
db. My concern is that after:

import sqlite3

db = sqlite3.connect("my_db.db")

1) This will open the db if it exists already, which is normally what
I will want. But...

2) My understanding is that if for whatever reason the db file is not
found, then the connect statement will create a new instance of the
db, which is what I normally would not want (Except at the time of
initial creation).

I'm just now in the process of reading up on SQLite, SQL, and Python's
DB API. So far I have seen no mention that the connect statement
returns anything if the db file does not already exist.

If I am understanding everything so far, I think that my situation
would be appropriate for using os.path.exists(). Is this correct?

Thanks!
boB
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-08-16 09:46:29 UTC
Permalink
Post by boB Stepp
db = sqlite3.connect("my_db.db")
1) This will open the db if it exists already, which is normally what
I will want. But...
2) My understanding is that if for whatever reason the db file is not
found, then the connect statement will create a new instance of the
db, which is what I normally would not want (Except at the time of
initial creation).
[...]
Post by boB Stepp
If I am understanding everything so far, I think that my situation
would be appropriate for using os.path.exists(). Is this correct?
Sure, why not?

If might not be an utterly bullet-proof solution, but it will do the
job for now and you can always revisit it later if needed.
--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Loading...