Monday, April 21, 2025

Move File to Another Folder - Python

import os, shutil

os.chdir('c:\\')

os.system('mkdir BACKUP')

shutil.move('c:\\Python38-64\\copy-me.txt', 'c:\\BACKUP')

This code uses the os and shutil modules to move a file called copy-me.txt from the c:\\Python38-64\\ directory to a new directory called BACKUP in the root directory of the C: drive (c:\\).

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

The os.chdir() function is used to change the current working directory to the root directory of the C: drive (c:\\). This is done to ensure that the new directory is created in the correct location.

The os.system() function is then called with the argument 'mkdir BACKUP'. This command is executed in the command prompt to create a new directory called BACKUP in the current working directory, which is the root directory of the C: drive in this case. The os.system() function allows us to execute a shell command from within our Python script.

The shutil.move() function is then called with two arguments: the source file (c:\\Python38-64\\copy-me.txt) and the destination directory (c:\\BACKUP). The shutil module provides a way to move files and directories in a platform-independent manner.

This code is useful for automating the backup of important files and ensuring that they are stored in a safe location. 

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