Monday, April 21, 2025

Copy File to Same Folder - Python

import os, shutil

os.chdir('c:\\Python38-64\\')

shutil.copy('copy-me.txt', 'backup-n-1.txt')

This code uses the os and shutil modules to copy a file called copy-me.txt from the current working directory (c:\\Python38-64\\) to a new file called backup-n-1.txt in the same directory.

import os, shutil

os.chdir('c:\\Python38-64\\')

The first line of code imports the os and shutil modules.

The os.chdir() function is used to change the current working directory to c:\\Python38-64\\. This is done to ensure that the source file, copy-me.txt, is located in the correct directory before it is copied.

shutil.copy('copy-me.txt', 'backup-n-1.txt')

The shutil.copy() function is then called with two arguments: the source file (copy-me.txt) and the destination file (backup-n-1.txt). The shutil module provides a way to copy files and directories in a platform-independent manner.

This code is useful for creating backups of important files in a way that is quick and easy to automate. However, it should be noted that overwriting an existing file with the same name as the destination file may result in the loss of the original file.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...