Python File I/O

Introduction

File I/O (Input/Output) in Python lets you read and write text files. It’s one of the most important skills for automation, data processing, and saving program results.

Opening a File

You use the open() function:

file = open("example.txt", "r")  # r = read mode
content = file.read()
print(content)
file.close()
      

Always close your files unless using with (shown later).

File Modes

Reading a File

with open("data.txt", "r") as f:
    text = f.read()
    print(text)
      

Reading Line by Line

with open("data.txt", "r") as f:
    for line in f:
        print("Line:", line.strip())
      

Writing to a File

with open("output.txt", "w") as f:
    f.write("Hello World!\n")
    f.write("Python rocks!")
      

Appending to a File

with open("output.txt", "a") as f:
    f.write("\nAnother line added.")
      

Checking If a File Exists

import os

if os.path.exists("data.txt"):
    print("File found.")
else:
    print("File missing.")
      

Deleting a File

import os
os.remove("oldfile.txt")
      

Why Use "with"?

Using with automatically closes the file, even if your code errors. It's the safest and cleanest way to work with files.

What's Next?

Now you can read, write, and manage files in Python. This opens the door to automation, logs, data processing, configuration systems, and more.