Reading and Writing Files in Python

 

Why Read and Write Files? 

Reading and writing files allows us to store and process data permanently, whether it's user inputs, logs, or structured data. It's like giving Python a memory beyond just running the program!

File Operations in a Nutshell

  • Reading files 
  • Writing files 
  • Appending to files 
  • Using best practices (like with statement) 

Reading a File

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

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

Reading Line by Line 

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

Other Read Methods 

Method Description
.read() Reads the entire file
.readline() Reads one line at a time
.readlines() Reads all lines into a list

Writing to a File

To write to a file, open it in write mode ('w'). Be careful—it will overwrite existing content! 

with open("example.txt", "w") as file:
    file.write("Hello, Python world!\n")

Appending to a File

Appending ('a' mode) adds new content without erasing existing data.

with open("example.txt", "a") as file:
    file.write("This is a new line!\n")

Best Practice: Using with Statement

Always use with open(...)! It automatically closes the file and prevents errors. No need for file.close()!

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

Summary 

Action Method
Open a file open("filename", "mode")
Read a file .read(), .readline(), .readlines()
Write to a file .write("text") (beware of 'w' mode!)
Append to a file .write("text") in 'a' mode
Best practice Use with open(...)

 

Post a Comment

0 Comments