Python Docs

Python Files & Directories — Full Cheat Sheet

Introduction

Python provides the os and shutil modules to interact with files and directories. These allow you to create, delete, rename, move, and explore your file system.

Check if a File Exists

Use os.path.exists() to check file availability.

import os

print(os.path.exists("myfile.txt"))

Create a New File

Using write mode "w" will create the file if it is missing.

f = open("newfile.txt", "w")
f.write("This is a new file.")
f.close()

Delete a File

Use os.remove() to delete a file. Always verify the file exists before deleting.

import os

if os.path.exists("oldfile.txt"):
  os.remove("oldfile.txt")
else:
  print("File does not exist")

Get Current Working Directory

os.getcwd() shows the directory where your Python script is running.

import os

print(os.getcwd())

List Files in a Directory

Use os.listdir() to see files and folders.

import os

print(os.listdir())

Create a Directory

Use os.mkdir() to create a single folder.

import os

os.mkdir("myfolder")

Rename a Directory

import os

os.rename("myfolder", "newfolder")

Remove a Directory

Use os.rmdir() — works only on empty directories.

import os

os.rmdir("newfolder")

Use shutil.rmtree() to delete non-empty folders.

import shutil

shutil.rmtree("myfolder")

Combine Paths Safely

Use os.path.join() for cross-platform paths.

import os

path = os.path.join("folder", "file.txt")
print(path)

Walk Through All Files & Subdirectories

os.walk() loops through folders, subfolders, and files.

import os

for root, dirs, files in os.walk("."):
  print("Root:", root)
  print("Directories:", dirs)
  print("Files:", files)

Summary Table

FunctionDescription
os.getcwd()Get current working directory
os.listdir()List files and directories
os.mkdir()Create directory
os.remove()Delete file
os.rmdir()Remove empty folder
shutil.rmtree()Remove directory along with its contents
os.path.exists()Check if file or folder exists
os.path.join()Combine paths safely
os.walk()Traverse directories recursively