472,958 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 software developers and data experts.

best way to check if a file exists?

What is the best way to check if a file already exists in the current
directory? I saw os.path.isfile(), but I'm not sure if that does more
than what I need.

I just want to check if a file of a certain name exists before the user
creates a new file of that name.

Thanks.
Oct 31 '06 #1
14 46175

John Salerno wrote:
What is the best way to check if a file already exists in the current
directory? I saw os.path.isfile(), but I'm not sure if that does more
than what I need.

I just want to check if a file of a certain name exists before the user
creates a new file of that name.

Thanks.
os.path.exists()?

Oct 31 '06 #2
At Tuesday 31/10/2006 18:01, John Salerno wrote:
>What is the best way to check if a file already exists in the current
directory? I saw os.path.isfile(), but I'm not sure if that does more
than what I need.
os.access(full_filename, os.F_OK)
http://docs.python.org/lib/os-file-dir.html
>I just want to check if a file of a certain name exists before the user
creates a new file of that name.
Remember that things may change between you check the name and you
actually create the file.
--
Gabriel Genellina
Softlab SRL

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ˇgratis!
ˇAbrí tu cuenta ya! - http://correo.yahoo.com.ar
Oct 31 '06 #3
On Oct 31, 4:01 pm, John Salerno <johnj...@NOSPAMgmail.comwrote:
What is the best way to check if a file already exists in the current
directory? I saw os.path.isfile(), but I'm not sure if that does more
than what I need.

I just want to check if a file of a certain name exists before the user
creates a new file of that name.
You could be more "pythonic", and simply try to create the file,
catching the exception if if fails. This works on linux:

try:
newfd = os.open('foobar', os.O_EXCL | os.O_CREAT)
new_file = os.fdopen(newdf)
except OSError, x:
if x[1] == 'File exists':
handle_file_exists()

[but beware unreliable on an NFS file system, from "man open":
O_EXCL is broken on NFS file
systems, programs which rely on it for performing locking tasks
will contain a race condition. The solution for performing atomic
file locking using a lockfile is to create a unique file on the
same fs (e.g., incorporating hostname and pid), use link(2) to make
a link to the lockfile. If link() returns 0, the lock is
successful.*
Otherwise, use stat(2) on the unique file to check if its
link count has increased to 2, in which case the lock is also
suc*cessful.]

Nov 1 '06 #4
ge**********@gmail.com writes:
On Oct 31, 4:01 pm, John Salerno <johnj...@NOSPAMgmail.comwrote:
What is the best way to check if a file already exists in the
current directory? I saw os.path.isfile(), but I'm not sure if
that does more than what I need.
I see that 'os.path.exists' has already been pointed out in a later
post.
You could be more "pythonic", and simply try to create the file,
catching the exception if if fails. This works on linux:

try:
newfd = os.open('foobar', os.O_EXCL | os.O_CREAT)
new_file = os.fdopen(newdf)
except OSError, x:
if x[1] == 'File exists':
handle_file_exists()
Are you sure that both of 'os.open' *and* 'os.fdopen' will only ever
raise OSError if the file already exists, and not for any other OS
errors?

--
\ "We have to go forth and crush every world view that doesn't |
`\ believe in tolerance and free speech." -- David Brin |
_o__) |
Ben Finney

Nov 1 '06 #5
On Tuesday 31 October 2006 16:01, John Salerno
wrote:
What is the best way to check if a file already
exists in the current directory? I saw
os.path.isfile(), but I'm not sure if that does
more than what I need.

I just want to check if a file of a certain
name exists before the user creates a new file
of that name.

Thanks.

How about something like one of these;

if os.path.isfile(vfileName) not True :
male file
or
if os.path.isfile (os.path.join(os.getcwd(),
vFileName) )==True :
do something
jim-on-linux

http://www.inqvista.com
Nov 1 '06 #6

John Salerno wrote:
What is the best way to check if a file already exists in the current
directory? I saw os.path.isfile(), but I'm not sure if that does more
than what I need.

I just want to check if a file of a certain name exists before the user
creates a new file of that name.

Thanks.
You could try to read the file, if that fails it doesn't exist:

try:
f = open('xxx')
except IOError:
f = open('xxx', 'w')
print "file doesn't exist"
print f

Nov 1 '06 #7
"wi******@hotmail.com" <ma**********@gmail.comwrites:
You could try to read the file, if that fails it doesn't exist:

try:
f = open('xxx')
except IOError:
f = open('xxx', 'w')
print "file doesn't exist"
print f
Except that there are other conditions than "File doesn't exist" that
can cause an 'open' to fail.

--
\ "If you continue running Windows, your system may become |
`\ unstable." -- Microsoft, Windows 95 BSOD message |
_o__) |
Ben Finney

Nov 1 '06 #8

Ben Finney wrote:
"wi******@hotmail.com" <ma**********@gmail.comwrites:
You could try to read the file, if that fails it doesn't exist:

try:
f = open('xxx')
except IOError:
f = open('xxx', 'w')
print "file doesn't exist"
print f

Except that there are other conditions than "File doesn't exist" that
can cause an 'open' to fail.
Ok, true. You can test explicit on non existence as follows, and then
decide to open the file

import errno
try:
f = open('xxx')
except IOError, e:
if e.errno == errno.ENOENT:
f = open('xxx', 'w')
print f
--
\ "If you continue running Windows, your system may become |
`\ unstable." -- Microsoft, Windows 95 BSOD message |
_o__) |
Ben Finney
Nov 1 '06 #9
"wi******@hotmail.com" <ma**********@gmail.comwrites:
Ben Finney wrote:
"wi******@hotmail.com" <ma**********@gmail.comwrites:
You could try to read the file, if that fails it doesn't exist:
Except that there are other conditions than "File doesn't exist"
that can cause an 'open' to fail.

Ok, true. You can test explicit on non existence as follows, and then
decide to open the file
Or you can simply use 'os.path.exists', as has been suggested several
times in this thread.

--
\ "The way to build large Python applications is to componentize |
`\ and loosely-couple the hell out of everything." -- Aahz |
_o__) |
Ben Finney

Nov 1 '06 #10
Ben Finney wrote:
"wi******@hotmail.com" <ma**********@gmail.comwrites:
Ben Finney wrote:
"wi******@hotmail.com" <ma**********@gmail.comwrites:
You could try to read the file, if that fails it doesn't exist:
>
Except that there are other conditions than "File doesn't exist"
that can cause an 'open' to fail.
Ok, true. You can test explicit on non existence as follows, and then
decide to open the file

Or you can simply use 'os.path.exists', as has been suggested several
times in this thread.
The O_CREAT|O_EXCL method pointed out elsethread is preferrable,
checking with "exists" and then creating if it returns false is racey.

Nov 1 '06 #11


On Nov 1, 3:44 pm, Ben Finney <bignose+hates-s...@benfinney.id.au>
wrote:
"witte...@hotmail.com" <martin.wi...@gmail.comwrites:
Ben Finney wrote:
"witte...@hotmail.com" <martin.wi...@gmail.comwrites:
You could try to read the file, if that fails it doesn't exist:
Except that there are other conditions than "File doesn't exist"
that can cause an 'open' to fail.
Ok, true. You can test explicit on non existence as follows, and then
decide to open the fileOr you can simply use 'os.path.exists', as has been suggested several
times in this thread.
os.path.exists() checks if a path exists, so a directory as argument
also returns True
--
\ "The way to build large Python applications is to componentize |
`\ and loosely-couple the hell out of everything." -- Aahz |
_o__) |
Ben Finney
Nov 1 '06 #12
wi******@hotmail.com wrote:
os.path.exists() checks if a path exists, so a directory as argument
also returns True
the original requirement was "to check if a file of a certain name
exists before the user creates a new file of that name".

if you want to check for files only, use the os.path.isfile predicate.

</F>

Nov 1 '06 #13
On Thu, 02 Nov 2006 01:44:25 +1100, Ben Finney wrote:
"wi******@hotmail.com" <ma**********@gmail.comwrites:
>Ben Finney wrote:
"wi******@hotmail.com" <ma**********@gmail.comwrites:
You could try to read the file, if that fails it doesn't exist:

Except that there are other conditions than "File doesn't exist"
that can cause an 'open' to fail.

Ok, true. You can test explicit on non existence as follows, and then
decide to open the file

Or you can simply use 'os.path.exists', as has been suggested several
times in this thread.
But there can be a race condition between os.path.exists returning True
and you trying to open the file, if some other process deletes or renames
the file in the meantime.

--
Steven.

Nov 2 '06 #14
Steven D'Aprano wrote:
But there can be a race condition between os.path.exists returning True
and you trying to open the file, if some other process deletes or renames
the file in the meantime.
if you'd used a threaded newsreader, you would have seen the code that
"as follows" was referring to, and you would probably also have noticed
that people have been pointing out the potential race problems several
times already.

</F>

Nov 2 '06 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Raymond | last post by:
Hi All: To find a file exists using the file name, I have tow routings on UNIX system. 1. access(2) 2. lstat(2) This tow function also can do. When the return value is "-1" and errno is...
2
by: Chris Fink | last post by:
I am using the System.IO.File class to determine if a file exists on a network share. The File.Exists method keeps returning false, even though the file does exist. The MSDN documentation...
7
by: Nathan Sokalski | last post by:
I have a form that allows the user to upload a file. Even though <input type="file" runat="server"> is intended to have the user choose the file using the browse button, it still allows them to...
3
by: akadelski | last post by:
I need a way to verify a file exists before I attempt to open it. Right now we are storing PDFs server-side and I need a way to either 1. Check if the physical file exists or 2. check if the URL...
5
by: sword | last post by:
How can I check whether a file exists?
4
by: Karim | last post by:
Hi, I need to write some code to figure out if a file exists before I overwrite it. I came up with this code, but not sure its the best.. bool isImgCached; TFilePtr pCachedFile =...
7
by: sprash | last post by:
Newbie question: I'm trying to determine if a file physically exists regardless of the permissions on it Using File.Exists() returns false if it physically exists but the process does not...
8
by: Sweetiecakes | last post by:
In our series of "probably something simple"... I am doing a File.Exists operation to check if a file exists. Let's assume that this file is C:/test.txt. Now, if I do...
2
Manikgisl
by: Manikgisl | last post by:
HI. How to check File exists in Web Share C# try { WebRequest request = HttpWebRequest.Create("http://www.microsoft.com/NonExistantFile.aspx"); request.Method = "HEAD"; // Just get...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.