Loading...

Go Back

Next page
Go Back Course Outline


Python Full Course


File Handling and Input Output in Python

📁 Python File Handling, Serialization & Directory Operations

1. File Handling in Python

Opening and Closing Files

Python uses the open() function to handle files.

File Modes

ModeDescription
'r'Read (default). File must exist.
'w'Write. Overwrites or creates file.
'a'Append. Adds to file or creates it.
'b'Binary mode. Used with r, w, a.
'+'Read and write.

Basic File Operations

                                        # Basic file writing
                                        file = open("sample.txt", "w")  # Open for writing
                                        file.write("Hello, Python!")
                                        file.close()  # Always close to save changes
Better Practice: Use with statement for automatic file closing.
                                        # Safer method using 'with'
                                        with open("sample.txt", "r") as file:
                                            content = file.read()
                                            print(content)
Hello, Python!

Reading and Writing Files

                                        # Writing multiple lines
                                        with open("greet.txt", "w") as f:
                                            f.write("Good morning!\n")
                                            f.write("Welcome to Python.")
# File contents (greet.txt): Good morning! Welcome to Python.
                                        # Reading entire file
                                        with open("greet.txt", "r") as f:
                                            print(f.read())
Good morning! Welcome to Python.
                                        # Reading line by line
                                        with open("greet.txt", "r") as f:
                                            for line in f:
                                                print(line.strip())
Good morning! Welcome to Python.

Appending to Files

                                        with open("greet.txt", "a") as f:
                                            f.write("\nHave a great day!")
# Updated greet.txt: Good morning! Welcome to Python. Have a great day!

Binary Files

                                        # Writing binary data
                                        with open("binary_file.dat", "wb") as f:
                                            f.write(b"This is binary data")
                                        
                                        # Reading binary data
                                        with open("binary_file.dat", "rb") as f:
                                            print(f.read())
b'This is binary data'




2. Data Serialization

JSON (JavaScript Object Notation)

                                        import json
                                        
                                        # Writing JSON
                                        data = {"name": "Emmanuel", "age": 22}
                                        with open("data.json", "w") as f:
                                            json.dump(data, f)
                                        
                                        # Reading JSON
                                        with open("data.json", "r") as f:
                                            person = json.load(f)
                                            print(person["name"])
Emmanuel

CSV (Comma-Separated Values)

                                        import csv
                                        
                                        # Writing CSV
                                        rows = [["Name", "Age"], ["Emmanuel", 22], ["John", 30]]
                                        with open("people.csv", "w", newline="") as f:
                                            writer = csv.writer(f)
                                            writer.writerows(rows)
                                        
                                        # Reading CSV
                                        with open("people.csv", "r") as f:
                                            reader = csv.reader(f)
                                            for row in reader:
                                                print(row)
['Name', 'Age'] ['Emmanuel', '22'] ['John', '30']

Pickle (Python Object Serialization)

                                        import pickle
                                        
                                        # Saving data
                                        data = {"name": "Emmanuel", "skills": ["Python", "Flutter"]}
                                        with open("data.pkl", "wb") as f:
                                            pickle.dump(data, f)
                                        
                                        # Loading data
                                        with open("data.pkl", "rb") as f:
                                            obj = pickle.load(f)
                                            print(obj["skills"])
['Python', 'Flutter']

3. Working with Directories

                                        import os
                                        
                                        # Create directory
                                        os.mkdir("test_folder")
                                        
                                        # Rename directory
                                        os.rename("test_folder", "renamed_folder")
                                        
                                        # Remove directory
                                        os.rmdir("renamed_folder")
                                        
                                        # List files
                                        print("Files in current directory:")
                                        for file in os.listdir("."):
                                            print(file)
                                        
                                        # Check existence
                                        print("\nFile checks:")
                                        print(os.path.exists("data.json"))  # True/False
                                        print(os.path.isfile("data.json"))  # True if file
                                        print(os.path.isdir("my_folder"))  # True if directory
Files in current directory: sample.txt greet.txt data.json people.csv data.pkl File checks: True True False




📋 Quick Reference Cheat Sheet

TaskFunction/Code
Open fileopen("file.txt", "mode")
Read filefile.read() or file.readlines()
Write to filefile.write("text")
JSON savejson.dump(data, file)
JSON loaddata = json.load(file)
CSV writecsv.writer(file).writerows(rows)
CSV readcsv.reader(file)
Pickle savepickle.dump(obj, file)
Pickle loadobj = pickle.load(file)
Create diros.mkdir("folder")
List filesos.listdir(".")
Go Back

Next page