473,804 Members | 4,795 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Safely renaming a file without overwriting

I want to rename a file, but only if the destination file name doesn't
already exist.

I can do this:

if os.path.exists( dest):
# skip file, raise an exception, make a backup...
do_something_el se()
else:
os.rename(src, dest)
But on a multi-user system, it is possible that dest is created in the
time period between checking if it exists and attempting the rename.

Is there any way to prevent this? Or do I just try to keep the check and
the rename as close together as possible, minimizing the chances and
hoping for the best?
--
Steven.

Oct 28 '06 #1
11 9893
Steven D'Aprano wrote:
I want to rename a file, but only if the destination file name
doesn't already exist.

I can do this:

if os.path.exists( dest):
# skip file, raise an exception, make a backup...
do_something_el se()
else:
os.rename(src, dest)
But on a multi-user system, it is possible that dest is created
in the time period between checking if it exists and attempting
the rename.

Is there any way to prevent this? Or do I just try to keep the
check and the rename as close together as possible, minimizing
the chances and hoping for the best?
1: Open the file with os.open

2: Lock the file exclusively -no other process can now access
it.

3: Use rename to rename the file; this causes a file system level
implicit unlink of the old file (it dissappears from the file
system) but the opening process can still access it.

4: close the file -the lock is removed and the rename
finalized.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber .org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
Oct 28 '06 #2
Wolfgang Draxinger schrieb:
Steven D'Aprano wrote:
>I want to rename a file, but only if the destination file name
doesn't already exist.

I can do this:

if os.path.exists( dest):
# skip file, raise an exception, make a backup...
do_something_el se()
else:
os.rename(src, dest)
But on a multi-user system, it is possible that dest is created
in the time period between checking if it exists and attempting
the rename.

Is there any way to prevent this? Or do I just try to keep the
check and the rename as close together as possible, minimizing
the chances and hoping for the best?

1: Open the file with os.open

2: Lock the file exclusively -no other process can now access
it.

3: Use rename to rename the file; this causes a file system level
implicit unlink of the old file (it dissappears from the file
system) but the opening process can still access it.

4: close the file -the lock is removed and the rename
finalized.
Where does that help for new files? The OP was right in assuming that a
race condition could occur when he tests for a file & then tries to
create it, as in the meantime it could have been created.

Diez
Oct 28 '06 #3
Diez B. Roggisch wrote:
>1: Open the file with os.open

2: Lock the file exclusively -no other process can now
access it.

3: Use rename to rename the file; this causes a file system
level implicit unlink of the old file (it dissappears from the
file system) but the opening process can still access it.

4: close the file -the lock is removed and the rename
finalized.
The open is to happen on the new file name with O_CREAT | O_EXCL
flags. Sorry, I forgot that to mention explicitly. However I
have not tried it yet, but it should work.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber .org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
Oct 28 '06 #4
Steven D'Aprano <st***@REMOVE.T HIS.cybersource .com.auwrites:
I want to rename a file, but only if the destination file name doesn't
already exist.

I can do this:

if os.path.exists( dest):
# skip file, raise an exception, make a backup...
do_something_el se()
else:
os.rename(src, dest)
But on a multi-user system, it is possible that dest is created in the
time period between checking if it exists and attempting the rename.

Is there any way to prevent this? Or do I just try to keep the check and
the rename as close together as possible, minimizing the chances and
hoping for the best?
--
Steven.
The answer, unfortunately, depends on the platform. I haven't tried, but it
looks like rename() will fail on Win32 if the file already exists. On Unix, you
can use link to rename the file - which will not overwrite the file if it
exists. Then use unlink to remove the src file.

Chetan
Oct 28 '06 #5
On Sat, 28 Oct 2006 13:38:14 +0200, Wolfgang Draxinger wrote:
>But on a multi-user system, it is possible that dest is created
in the time period between checking if it exists and attempting
the rename.

Is there any way to prevent this? Or do I just try to keep the
check and the rename as close together as possible, minimizing
the chances and hoping for the best?

1: Open the file with os.open
Open "the" file? There are potentially two files -- the source and
destination. I only want to do the rename if the destination
*doesn't* exist, so there is no destination file to open. How will it help
me to lock the source file? Have I misunderstood?
--
Steven.

Oct 28 '06 #6
On Sat, 28 Oct 2006 16:48:37 +0200, Diez B. Roggisch wrote:
Where does that help for new files? The OP was right in assuming that a
race condition could occur when he tests for a file & then tries to
create it, as in the meantime it could have been created.
Ah! "Race condition" -- that was the term I was looking for ... now maybe
I'll have some better results with Google.

--
Steven.

Oct 28 '06 #7
Steven D'Aprano wrote:
Open "the" file? There are potentially two files -- the source
and destination. I only want to do the rename if the
destination *doesn't* exist, so there is no destination file to
open. How will it help me to lock the source file? Have I
misunderstood?
I forgot to say, to open the source file with O_CREAT | O_EXCL.
The open will fail if the file already exists. By locking the
file no other process will be able to access it, but the process
that holds the lock can do with it anything. This includes to
rename an existing file to the name of the opened one - the
previously created placeholder file will get unlinked before,
but there is _probably_ no way that any process can intercept
this. It is an interesting thing, that files that are opened
remain fully usable and accessible if you unlink them as long
you don't close them. You have to close it, to remove all
remains of it.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber .org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
Oct 28 '06 #8
On Sun, 29 Oct 2006 00:29:06 +0200, Wolfgang Draxinger wrote:
Steven D'Aprano wrote:
>Open "the" file? There are potentially two files -- the source
and destination. I only want to do the rename if the
destination *doesn't* exist, so there is no destination file to
open. How will it help me to lock the source file? Have I
misunderstoo d?

I forgot to say, to open the source file with O_CREAT | O_EXCL.
The open will fail if the file already exists.
But the source file always exists, otherwise there is nothing to rename!
Do you mean, open the destination filename?

--
Steven.

Oct 28 '06 #9
Steven D'Aprano wrote:
But the source file always exists, otherwise there is nothing
to rename! Do you mean, open the destination filename?
Of course I meant the destination file. Someone please spill some
ice chilled water over me to get me awake again. Time to go to
bed :-P before I make more dumb mistakes/typos...

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber .org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
Oct 28 '06 #10

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

Similar topics

1
7388
by: Ellixis | last post by:
Hello, How can I use fwrite() and fseek() in order to write data in the middle (or anywhere else) of a file without overwriting existing data ? People told me that I should load the file into memory (a variable) and use concatenation. But, according to me, It isn't clean to load an entire file into
2
2788
by: Amy G | last post by:
I am looking to make this code a little "nicer"... any suggestions??? I want to do a "read+" where I would be able to first read the contents of the file... then either close the file out or write to the file without appending. I want to overwrite the content. vacation_message = "blah blah blah" f_vm=open("/home/%s/.vacation.msg" %userid, 'r') lines=f_vm.readlines() f_vm.close()
8
3296
by: Stewart | last post by:
is there any way this can be done? I've looked at the help files and checked out as many tutorials as i could find on the net (as always) but no joy. thanks
3
23961
by: Jonathan Buckland | last post by:
Can someone give me an example how to append data without having to load the complete XML file. Is this possible? Jonathan
4
8335
by: nan | last post by:
Hi all. Anyone has an idea of how to open a file without know the complete name of it, without opening the directory (with opendir) and test each file? For example, I have this: 1070471736268 and the complete file name is:
3
2541
by: Sarav | last post by:
Hi All, I need to upload an XML file via an client side ActiveX control. I searched the web but everywhere got the samples of using file control alone. How can I upload a file into my web server without using the <input type ="file" ....> control. I need the same for Download also. Without displaying the Save as dialog box. Why I am asking this is I am going to handle this with my Client side ActiveX control.
0
1802
by: nettynet | last post by:
I'm really new in java. I'm trying to read 8000 URL files and write to a file. It's a kind of combining all files together...not overwritten. This is the URL of my all files http://www.ifi.unizh.ch/ddis/ph/2006/08/ ... These files are .owl....and I store all of them in a directory. This is source code java that i wrote...it doesnt work as I want.... In fact, I just dont know how to call the files directly from the URL ... Please advice. ...
0
751
by: Cowboy \(Gregory A. Beamer\) | last post by:
As I have seen this question in a few different forums lately, I posted a new entry to my blog about how to deploy to a web server without overwriting config values: http://gregorybeamer.spaces.live.com/blog/cns!B036196EAF9B34A8!923.entry There are other kludgy ways I have seen, but this one works the best, as you can run a normal publish and then xcopy the bits to the server. -- Gregory A. Beamer
5
1249
by: Reckoner | last post by:
I have multiple packages that have many of the same function names. Is it possible to do from package1 import * from package2 import * without overwriting similarly named objects from package1 with material in package2? How about a way to do this that at least gives a warning?
0
9706
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10577
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10077
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6853
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4299
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3820
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2991
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.