Hai friends
I have a small problem with my code...
I want to copy an existing file (its a model MS Excel file) to a new file & name it with the current date...
First I tried to create the model Excel file, but when I opened it, it had only one sheet inside it, so I tried to copy the existing file, but I couldnt find any bright ideas... can anyone show me a way?


import sys
import win32com.client

fileVM = open('e:/disk/vm.xls','a')
fileVM.close()

The above code creates the file with a single Excel Sheet inside it. But my model file has a lot of info, so I wud prefer to copy & then rename the existing file...

Dani AI

Generated

showed the root cause: opening an Excel file with Python's open(..., 'a') simply creates a new (mostly empty) file that Excel treats as a fresh workbook. Excel files are binary containers, so text-mode file ops won't duplicate the workbook structure or sheets. Copying at the OS level is the right approach rather than trying to recreate the file by hand.

and were on the right track with the shutil approach. A robust pattern is: build a timestamped filename (so the model stays untouched), verify the source exists, and perform a binary copy. The code below is a concise, readable example using modern path handling and preserving timestamps:

from pathlib import Path
import shutil
from datetime import datetime

src = Path(r"E:\disk\vm.xls")
dst = src.with_name(f"{src.stem}_{datetime.now():%Y%m%d}.xls")

try:
    shutil.copy2(src, dst)
except Exception as e:
    print("copy failed:", e)

Troubleshooting notes drawn from the thread: confirm the source file actually exists before copying; on Windows Excel may lock the file (causing PermissionError) so close Excel or use the Excel COM API to SaveAs if a copy must be made while the workbook is open; use os.replace/os.rename only when moving/renaming is acceptable (they do not duplicate the model). Prefer pathlib for clearer path code and use shutil.copy2 when preserving file timestamps is important.

Recommended Answers

All 4 Replies

are you just looking for a was to copy a file(I might be missing something)

import shutil
shutil.copy2('e:/disk/vm.xls', 'new_name_of_copy')

I have only tested this on my linux system, but it should also work on a windows platform.

You may want to use shutil.copy(sourcefile, destinationfile), it gives copy the current date, shutil.copy2(sourcefile, destinationfile) gives the date of the file you copy.

You may want to use shutil.copy(sourcefile, destinationfile), it gives copy the current date, shutil.copy2(sourcefile, destinationfile) gives the date of the file you copy.

good point, I was not sure on the exact difference

Thanks guys , its working fine with windows as well...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.