-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?

4
  • change the destination (the second parameter to shutil.copy) Commented Jun 20, 2017 at 21:00
  • 1
    stackoverflow.com/questions/541390/… Commented Jun 20, 2017 at 21:01
  • What type is filename? Is it a string? In which case, you can split on the . and change the first part, then join() again. Commented Jun 20, 2017 at 21:02
  • I know that, but if I do like + "(1)" the (1) comes after the extension name. It would be like hi.txt(1). Commented Jun 20, 2017 at 21:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.