-2

I would like to copy a file, but I want the new file to be named something different, like having a (1) next to the name without changing the extension.

Here is my code:

import shutil
from tkinter import *
from tkinter.filedialog import askopenfilename
import os


filename = askopenfilename()

file_name, file_extension = os.path.splitext(filename)

dec = "_dec"

newfile = file_name + dec


copied = str.join(newfile, file_extension)


shutil.copy(filename, copied )

master = Tk()

w = Message(master, text="Copied!", width = 100)
w.pack()

mainloop()

How would I get filename to have a (1) at the end of the name without touching the extension?

Darksp33d
  • 17
  • 4

1 Answers1

2

You can use os.path.splitext to get the root and extension. Then you can increment the filename with a number until it does not exist, add the extension back, and save the file.