Besides reading and writing contents, programs often need to manage files as a whole: check whether a file exists, find its size, copy, rename or delete it, and list a folder. The standard modules os, os.path and shutil provide these operations.
Useful functions
Function
Purpose
os.path.exists(p)
True if a file or folder p exists
os.path.isfile(p), os.path.isdir(p)
True if p is an existing file / folder
os.path.getsize(p)
Size of the file in bytes
os.stat(p)
Detailed information: size (st_size), modification time and more
os.listdir(p)
Names of the entries in folder p (in no particular order)
os.getcwd(), os.chdir(p)
Get / change the current working directory
os.mkdir(p)
Create a folder
os.rename(a, b)
Rename or move a file
os.remove(p)
Delete a file
os.rmdir(p)
Delete an empty folder
shutil.copy(src, dst)
Copy a file’s contents (and permissions)
shutil.rmtree(p)
Delete a folder and everything in it (use with great care)
The newer pathlib module offers the same operations through Path objects, for example Path("notes.txt").exists() and Path("notes.txt").stat().st_size.
Key takeaways
os.path.exists, isfile, isdir and getsize inspect files.
shutil.copy copies; os.rename renames or moves; os.remove deletes a file.
os.rmdir removes only empty folders; shutil.rmtree removes a whole tree.
os.listdir lists a folder in arbitrary order; sort it if order matters.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a program that makes a backup copy of data.txt named data_backup.txt, but only if data.txt exists, and prints the size of the backup.
Show worked answer
import os, shutil, then if os.path.exists("data.txt"): shutil.copy("data.txt", "data_backup.txt") followed by print(os.path.getsize("data_backup.txt"), "bytes"), and else: print("data.txt not found"). Checking first avoids FileNotFoundError; shutil.copy copies the contents; getsize confirms the backup has the same size as the original.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/functions-and-file-handling-in-python/copying-deleting-and-inspecting-files/ to read this page.