LANGUAGE & SYNTAX · PYTHON

12 · Files

Read, write, and work with files in Python.

Python can read and write files.

Common uses:

01

open()

open() opens a file.

Syntax

open(file_path, mode)

Common modes

r → read
w → write
a → append
02

Read a File

Example

file = open("orders.txt", "r")

content = file.read()

print(content)

file.close()

The file is opened, read, and then closed.

03

with open()

with open() is the recommended pattern because Python closes the file automatically.

Example

with open("orders.txt", "r") as file:
    content = file.read()
04

read()

Reads the entire file.

Example

with open("orders.txt", "r") as file:
    content = file.read()

print(content)
05

readline()

Reads one line from a file.

Example

with open("orders.txt", "r") as file:
    first_line = file.readline()
06

readlines()

Reads all lines into a list.

Example

with open("orders.txt", "r") as file:
    lines = file.readlines()

Possible result

[
    "Order 1001\n",
    "Order 1002\n",
    "Order 1003\n"
]
07

Loop Through a File

Example

with open("orders.txt", "r") as file:
    for line in file:
        print(line.strip())

Reads the file one line at a time.

08

Write a File

Use mode:

w

Example

with open("result.txt", "w") as file:
    file.write("Completed")

Important: w replaces existing content.

09

Write Multiple Lines

Example

with open("result.txt", "w") as file:
    file.write("Order 1001\n")
    file.write("Order 1002\n")

Result

Order 1001
Order 1002
10

Append

Use mode:

a

Example

with open("log.txt", "a") as file:
    file.write("New order created\n")

Append adds content to the end of the file.

11

File Encoding

Recommended example

with open(
    "orders.txt",
    "r",
    encoding="utf-8"
) as file:
    content = file.read()

UTF-8 helps Python correctly read many languages and characters.

12

Relative Path

Example

"orders.txt"

Another example

"data/orders.txt"

A relative path is based on the current working directory.

13

Absolute Path

macOS example

/Users/rebecca/project/data/orders.txt

Windows example

C:\Users\Rebecca\project\data\orders.txt
14

Check File Exists

Example

from pathlib import Path

file_path = Path("orders.txt")

if file_path.exists():
    print("File exists")
15

Practical Example

orders.txt:

1001,Copper,10
1002,Aluminum,20
1003,Nickel,5

Python:

with open("orders.txt", "r") as file:
    for line in file:
        order_id, product, quantity = line.strip().split(",")

        print(order_id, product, quantity)

Output:

1001 Copper 10
1002 Aluminum 20
1003 Nickel 5

Each line is:

  1. read
  2. cleaned with strip()
  3. split by comma
  4. assigned to variables
↑