Python Forum
Improving code to autorename if filename exists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Improving code to autorename if filename exists
#1
Hi all, I have a part of my code that I would like to give a little upgrade.
import os
import shutil

dest = '/path/to/dest_folder'
src = '/path/to/src_folder'

for root, subdirs, files in os.walk(src):
    for file in files:
        path = os.path.join(root, file)
        shutil.move(path, dest)
This code replaces files from a folder and its subfolders to one destination-folder. The problem here is: If there are 2 files with thesame filename I get an error:
Quote:shutil.Error: Destination path '/path/to/dest_folder/filename' already exists

I'd like to change this code so it automaticly renames the file if it already exists in the destination-folder because thesame filename doesn't mean it has thesame content so I don't want to overwrite files in the destination-folder.

I've been thinking about using a timestamp but I'm not sure If and how to do it. Any tips? Ideas?

Thanks :)
Reply


Messages In This Thread
Improving code to autorename if filename exists - by Den0st - Sep-21-2019, 11:56 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help improving function that reads file into list of tuples t4keheart 6 4,473 Nov-03-2020, 04:58 AM
Last Post: ndc85430
  p]Why os.path.exists("abc/d") and os.path.exists("abc/D") treat same rajeev1729 1 2,854 May-27-2020, 08:34 AM
Last Post: DeaD_EyE
  Improving my understanding of functions and methods menator01 2 2,898 Apr-24-2020, 06:26 AM
Last Post: menator01
  Improving bot SheeppOSU 0 35,297 Jun-01-2019, 08:06 PM
Last Post: SheeppOSU
  Is there a way of improving this leaderboard system? Zelpha 2 4,788 Feb-11-2019, 06:32 PM
Last Post: ichabod801
  Improving Efficiency of SVM by various available kernels Sachtech 0 2,691 Apr-09-2018, 07:29 AM
Last Post: Sachtech
  Question on runtime and improving nested for loops ackmondual 1 3,776 Jun-13-2017, 11:11 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020