Home > Enterprise >  Copy a file to a new folder and rename it in python
Copy a file to a new folder and rename it in python

Time:02-23

I’m trying to copy an xls file to a new folder and there renaming it as xlsx file but I’m getting several errors. I want to change the name because the xls file could be corrupt. The input file is given by the user and I want to create the new folder in the same path as the input file is in and copy the file in the new folder.

I’m able to create new folder but unable to copy file there moreover if I rename the file therein only the file still remains corrupt.

I want a solution such that if the file is copied and renamed the .xlsx file opens without any pop up.

CodePudding user response:

If your file is corrupted, there is no way to fix it by changing the name, the following code will only help you copy the file and create the folder:

import os
from shutil import copyfile

if not os.path.exists("folder"):
    os.mkdir("folder")

target = os.path.join(os.getcwd(), "folder")

filename = input("filename: ")

if os.path.exists(filename):
    target_filename = filename.replace("xls", "xlsx")
    copyfile(filename, os.path.join(target, target_filename))
    print("success")
else:
    print("failure")
  • Related