473,785 Members | 2,282 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copyfile avoiding overwrites and race conditions

Here is a code fragment, where I am trying to copy a file, avoiding
overwrites and race conditions. The filename gets a '02','03','04' etc
appended to the end if a file with that name already exists.

I know the writing of the single space is overkill, but I am surprised
I cannot find an example of this floating around the web and newsgroups

my understanding of 'os.open' and 'os.fdopen' is minimal

## start fragment

i = 0
while True:

if i >= 100: raise RanOutFileNames Error(fullpath)
i += 1

if i > 1:
name0 = '%s_%02i%s' % (suggested_name , i, file_extension)
else:
assert i == 1
name0 = '%s%s' % (suggested_name , file_extension)
fullpath = os.path.join(pa th0, name0)

# create dummy file, force overwrite

try:
fd = os.open(
fullpath,
os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except OSError:
continue

# is this really necessary?
file = os.fdopen(fd, "w")
file.write(' ')
file.close()

shutil.copyfile (original_filep ath, fullpath)

return fullpath

## end fragment

Jun 16 '06 #1
2 3649
ma*****@gmail.c om wrote:
Here is a code fragment, where I am trying to copy a file, avoiding
overwrites and race conditions. The filename gets a '02','03','04' etc
appended to the end if a file with that name already exists.

I know the writing of the single space is overkill, but I am surprised
I cannot find an example of this floating around the web and newsgroups

my understanding of 'os.open' and 'os.fdopen' is minimal

## start fragment

i = 0
while True:

if i >= 100: raise RanOutFileNames Error(fullpath)
i += 1

if i > 1:
name0 = '%s_%02i%s' % (suggested_name , i, file_extension)
else:
assert i == 1
name0 = '%s%s' % (suggested_name , file_extension)
fullpath = os.path.join(pa th0, name0)

# create dummy file, force overwrite

try:
fd = os.open(
fullpath,
os.O_CREAT | os.O_EXCL | os.O_WRONLY)
except OSError:
continue

# is this really necessary?
file = os.fdopen(fd, "w")
file.write(' ')
file.close()

shutil.copyfile (original_filep ath, fullpath)

return fullpath

## end fragment

I guess my approach would be different. To eliminate any race
conditions, I would keep a small text file that always contained
the next filename that is to be written. Something like:

nextfiletowrite =/path/filename006.dat

I would try to get a lock on this file, read it, extract next
filename, increment the counter portion of the filename,
write it back out and unlock it. Now I have the name of the
file to write that is unique to my instance and I can write it
without worrying about other processes.

Hope this helps.

-Larry Bates
Jun 19 '06 #2
Larry Bates wrote:
I guess my approach would be different. To eliminate any race
conditions, I would keep a small text file that always contained
the next filename that is to be written. Something like:

nextfiletowrite =/path/filename006.dat

I would try to get a lock on this file, read it, extract next
filename, increment the counter portion of the filename,
write it back out and unlock it. Now I have the name of the
file to write that is unique to my instance and I can write it
without worrying about other processes.


Yes, that would work as well

but I get the feeling that

1) most people don't write to an automatically incrementing filename
2) the few who do don't sweat the race condition

Thanks for your reply

Manuel

Jun 19 '06 #3

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

Similar topics

5
15854
by: GIMME | last post by:
One of my coworkers insists that one should never use static methods because race conditions exist. Thinking along the lines that all variable assignments are assignments to static variables. He's wrong. Right? Two users in a web session could both access a static method at the same time and never have any trouble.
18
5862
by: Urs Vogel | last post by:
Hi I wrote an application server (a remoting sinlgeton), where processes must be stopped in very rare cases, done thru a Thread.Abort(). Occasionally, and only after a Thread.Abort(), this component becomes instabile, throwing a Windows like error (access violation on 0x00000002), not an framework exception. The component and all of its subcomponents are 100% managed code. What could go wrong with Thread.Abort()? Thanks for any hints.
4
6040
by: ad | last post by:
I am finding to copyfile in the online document. But I only find the namespace : Namespace: Microsoft.VisualBasic.FileIO How can I copyfile in c#?
11
5248
by: brother52 | last post by:
I am using My.Computer.FileSystem.CopyFile() to copy a bunch of files from one directoy to another, and would like to display a progress bar on the screen for each file being copied. Is this possible?
5
2275
by: mars | last post by:
I use TurboGears to do some web service. TurboGears use cherrypy. When web browser access this site, the cherrypy will call my python program. So my program looks like a lib. When web browser access the site, the http server will fock a process or gerenate a thread. I need share some data or operate some files. How can I prevent from race conditions. Is there any way can I lock this. Thank you in advance!
5
1840
Plater
by: Plater | last post by:
So after my previous troubles I now have asynchonous xmlHTTPRequests going. I send a request on an interval set for 5seconds. First the FF trouble: Sometimes when I refresh the page, I'll get an error saying "returnObjById is not defined". Now, returnObjById() is my own function that exists and after about 3 of these errors it decides that the function exists and uses it just fine. It seems to be related to the onreadystatechange of the...
1
1545
by: Larry Bates | last post by:
I have a need to implement a drop folder upload mechanism for secure uploading of files to a server. At first glance this appears that it would be an easy application to write. Then I begin to think about the race conditions that exist between the process that will wake up to upload the files and the fact that the user can add additional files to the drop folder at any point in time. I would like to clear out files/folders after they have...
2
1958
by: ian.cross | last post by:
Hi everyone, If a multi-threaded .NET program creates a race condition updating a List (for example), could this cause a memory leak/overwritten memory/ access to another objects' private memory? Basically I'd like to know if sloppy multi-threaded code can break the CLR's guarantees of 'managed code' - garbage collection, bounds-checking, type safety etc? First time poster, long time reader - be gentle.
0
1838
by: moltendorf | last post by:
I've been trying to find a suitable method for preventing race conditions in my own code. Currently I'm using a file and the flock function to prevent code in other threads from executing at the same time. For example: <?php $pointer = fopen ('./thread.lock', 'a+'); flock ($pointer, LOCK_EX);
0
9484
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
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...
1
10097
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8983
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7505
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6742
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
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
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
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.