Back to: Python Programming
Python can copy the contents of a file. To do this we use the “shutil” module. Put a file called “test.txt” in the project folder.
Copy
There are three functions to copy a file:
- copyfile() – copies the contents of a file
- copy() – everything copyfile() does + permissions + destination
- copy2() – everything copy() does + metadata (file create and modify times)
The arguments for all three are the same:
shutil.copyfile(‘source.txt’,’detination.txt) # <--assumes source.txt is in the project folder
or if the destination is in another path:
shutil.copyfile(‘source.txt’,’c:\\data\\temp\\detination.txt”) # <-- copies to specified path
Usage:
import shutil
shutil.copyfile("test.txt", "copy.txt")
Move
Python can ‘move’ a file or directory by importing the “os” module. To move a file from the “project folder” to a directory c:\data – we follow these steps. We will use a conditional [if / else] to check for the existence of an existing file so we don’t overwrite it, we also check if a file to move actually exists [try / except] and in the event of an error, we throw an exception and print a message.
import os
source = "test.txt" # <- no path so it’s in projects folder
destination = "c:\\data\\test.txt"
try: # <-- code within 'try' 'except' block in case file not found
if os.path.exists(destination):
print("This file already exists!")
else:
os.replace(source,destination)
print(source+" was moved")
except FileNotFoundError:
print(source+" was not found")
The source and destination for moving can also be a folder name.
import os
source = "Test-Folder"
destination = "c:\\data\\Test-Folder"
try: # <-- code within 'try' 'except' block in case file not found
if os.path.exists(destination):
print("This directory already exists!")
else:
os.replace(source,destination)
print(source+" was moved")
except FileNotFoundError:
print(source+" was not found")
Delete (be careful with this one)
Python can ‘delete’ a file or directory by importing the “os” module. Put a “test.txt” file in the projects folder first.
import os
os.remove("test.txt")
A slightly tidier and more refined way to do it:
import os
path = "test.txt"
os.remove(path)
On running the code a second time, the file will not be found so we need to do some exception handling:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.txt'
Using a try block we can use the exception except FileNotFoundError:
import os
path = "test.txt"
try:
os.remove(path)
except FileNotFoundError:
print("File not found!")
If you try to delete a file that doesn’t exist, your program will not be interrupted and will instead print a warning.
Different functions are used to delete files, empty folders and folders containing files. To delete an empty folder – put an empty folder in your projects directory:
import os
path = "empty_folder"
try:
os.rmdir(path)
except FileNotFoundError:
print("Folder not found!")
else:
print(path+" has been deleted.")
If this folder contains a file, an OSError exception will occur so we need to handle it:
import os
path = "temp_folder"
try:
os.rmdir(path)
except FileNotFoundError:
print("Folder not found!")
except OSError:
print(f"The folder {path} is not empty.")
else:
print(path+" has been deleted.")
To delete a non-empty folder – use shutil.rmtree(path) – this is a DANGEROUS function.
import os
import shutil
path = "temp_folder"
try:
shutil.rmtree(path)
except FileNotFoundError:
print("Folder not found!")
else:
print(path+" has been deleted.")