🎓 A1Learner
🔍

Python File Paths

A path is the address of a file on disk.

Join path parts

join() glues a folder name and a file name safely. It uses the slash your system expects.

import os

path = os.path.join("data", "notes.txt")
print(path)

Ask if a path exists

exists() answers True or False. It is safe to call on any path.

import os

with open("notes.txt", "w") as f:
    f.write("hi")
print(os.path.exists("notes.txt"))
print(os.path.exists("nope.txt"))

Make a folder, then join

mkdir() makes one new folder. The if guard keeps the code safe to run again.

import os

if not os.path.exists("data"):
    os.mkdir("data")
path = os.path.join("data", "a.txt")
with open(path, "w") as f:
    f.write("inside")
print(os.path.exists(path))

Name the current folder

getcwd() returns the current folder as text. We do not print it here. Its value differs on each computer.

import os

current_folder = os.getcwd()

Example

import os

if not os.path.exists("files"):
    os.mkdir("files")

path = os.path.join("files", "story.txt")

with open(path, "w") as f:
    f.write("A short story lives here.\n")

print(os.path.exists(path))

with open(path, "r") as f:
    print(f.read().strip())

Key points

  • Relative path: an address that starts from the current folder
  • Absolute path: a full address that starts from the top of the disk
  • Use os.path.join() to build a path.
  • It adds the right slashes for you.
  • Use os.path.exists() to ask if a path is there.
  • It returns True or False.
  • Use os.getcwd() to get the current folder as text
  • Use os.mkdir() to make one new folder
  • A path tells a program where to find a file on disk.

In this example, the program makes a files folder if it is missing. join() builds the path to story.txt inside it. The program writes one line to that path. exists() then checks the path and prints True. The last block reads the file and prints its line without the newline.

Note

Paths differ between computers.

Print True or False checks, not raw paths.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which function builds a path from parts safely?