473,386 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 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 46219

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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.