Python Tutorial menu

Python File Handling

File handling lets your program save data to a file and read it back later.

Opening a File

The open() function takes a file name and a mode:

ModeMeaning
"r"Read (default). Error if the file does not exist
"w"Write. Creates the file, or erases it if it exists
"a"Append. Adds to the end of the file
"x"Create. Error if the file already exists

Add "b" for binary files like images, for example "rb".

Writing a File

Example

python
with open("students.txt", "w") as f:
    f.write("Ali\n")
    f.write("Ayesha\n")
    f.write("Hamza\n")
print("File saved")
Output
File saved

The with statement closes the file for you when the block ends, even if an error happens. Always use it.

write() does not add a new line by itself. Put \n at the end of each line yourself.

Reading a File

Example

python
with open("students.txt", "r") as f:
    content = f.read()
print(content)
Output
Ali
Ayesha
Hamza

Other ways to read:

MethodReturns
read()The whole file as one string
readline()The next single line
readlines()A list of all lines

Reading Line by Line

Looping over the file reads one line at a time. This works well even for very large files.

Example

python
with open("students.txt") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())
Output
1 Ali
2 Ayesha
3 Hamza

strip() removes the \n at the end of each line.

Appending to a File

Example

python
with open("students.txt", "a") as f:
    f.write("Sana\n")

with open("students.txt") as f:
    print(f.readlines())
Output
['Ali\n', 'Ayesha\n', 'Hamza\n', 'Sana\n']

A Small Practical Example

Save daily sales, then calculate the total:

Example

python
sales = [1500, 2300, 1800]

with open("sales.txt", "w") as f:
    for amount in sales:
        f.write(f"{amount}\n")

total = 0
with open("sales.txt") as f:
    for line in f:
        total += int(line)
print("Total sales: Rs", total)
Output
Total sales: Rs 5600

Checking and Deleting Files

Use the os module:

Example

python
import os

if os.path.exists("sales.txt"):
    os.remove("sales.txt")
    print("Deleted")
else:
    print("File not found")
Output
Deleted

Checking first avoids a FileNotFoundError.

Exercise

Exercise

Which mode adds new text to the end of a file without erasing what is already there?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp