Opening and Closing Files in Python

 

Why Work with Files?

Files help us store and retrieve data permanently. Whether you're saving user input, logging errors, or working with data files, file handling is an essential skill!

File Handling Basics

  • Opening a file 
  • Reading or writing data 
  • Closing the file (VERY IMPORTANT!)

Opening a File

Before we can read or write a file, we need to open it using Python's built-in open() function.

file = open("example.txt", "r")  # 'r' means read mode

File Modes

Mode Description
'r' Read mode (default)
'w' Write mode (creates a new file or overwrites existing)
'a' Append mode (adds to an existing file)
'x' Exclusive creation (fails if the file exists)

Reading a File

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

Read Line by Line

file = open("example.txt", "r")
for line in file:
    print(line.strip())  # Removes extra newlines
file.close()

Writing to a File

file = open("example.txt", "w")
file.write("Hello, Python world!\n")
file.close()

Using 'w' mode will erase the file if it exists!

Appending to a File

file = open("example.txt", "a")
file.write("This is a new line!\n")
file.close()

Best Practice: Using with Statement 

The with statement automatically closes the file, so we don’t forget!

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# File automatically closed here! 

Summary 

Action Method
Open a file open("filename", "mode")
Read a file .read(), .readline(), .readlines()
Write to a file .write("text") (be careful with 'w' mode!)
Append to a file .write("text") in 'a' mode
Close a file .close() (or use with)

 

Post a Comment

0 Comments