Skip to content
Justice Tech School

Files and Folders with os

The os and pathlib modules manage files. os.path.exists checks, os.rename renames, os.remove deletes a file, os.listdir lists a folder and os.makedirs creates folders. Be careful: deleting cannot be undone.

Example
import os, tempfile
folder = tempfile.mkdtemp()
file = os.path.join(folder, "a.txt")
open(file, "w").close()
print(os.listdir(folder))
os.rename(file, os.path.join(folder, "b.txt"))
print(os.listdir(folder))
os.remove(os.path.join(folder, "b.txt"))
print(os.listdir(folder))

Result

['a.txt']
['b.txt']
[]

Exercise

Delete a file.

os.("old.txt")

Quiz Test

Which function lists the files in a folder?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.