Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 51091
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T16:41:44+00:00 2026-05-10T16:41:44+00:00

Still ‘diving in’ to Python, and want to make sure I’m not overlooking something.

  • 0

Still ‘diving in’ to Python, and want to make sure I’m not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function – and I’m just wondering if there is a better way to do this? Thanks!

def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name):      file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]     counter += 1 return file_name 

I really do require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I’m not looking for a more robust method (tho’ I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T16:41:45+00:00Added an answer on May 10, 2026 at 4:41 pm

    One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn’t be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.

    To get around it, the best approach is to actually try create the file in such a way that you’ll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here’s your code modified to use this approach (returning a (file, filename) tuple):

    def unique_file(file_name):     counter = 1     file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')     while 1:         try:             fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)             return os.fdopen(fd), file_name         except OSError:             pass         file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]         counter += 1 

    [Edit] Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here’s an example of using it (keeping a similar interface):

    def unique_file(file_name):     dirname, filename = os.path.split(file_name)     prefix, suffix = os.path.splitext(filename)      fd, filename = tempfile.mkstemp(suffix, prefix+'_', dirname)     return os.fdopen(fd), filename  >>> f, filename=unique_file('/home/some_dir/foo.txt') >>> print filename /home/some_dir/foo_z8f_2Z.txt 

    The only downside with this approach is that you will always get a filename with some random characters in it, as there’s no attempt to create an unmodified file (/home/some_dir/foo.txt) first. You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 168k
  • Answers 168k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer As the time it takes for a thumbnail to be… May 12, 2026 at 1:46 pm
  • Editorial Team
    Editorial Team added an answer I think it's Firebird. Even Cte's are supported in Firebird… May 12, 2026 at 1:46 pm
  • Editorial Team
    Editorial Team added an answer imagecopy() or imagecopymerge(). It's documentation brings exemples too. May 12, 2026 at 1:46 pm

Related Questions

Still 'diving in' to Python, and want to make sure I'm not overlooking something.
still new to the world of linq, and i need some help flatening a
Still struggling to understand what best practices are with respect to macros. I'm attempting
Still new to Objective C, and I'm having some trouble that I just can't
still trying to find where i would use the yield keyword in a real

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.