Python File Handling – Read, Write, Delete Files with Examples

⏱︎

Read time:

1–2 minutes
file-handling-in-python

Introduction

File handling is a fundamental skill in Python programming. Whether you’re saving data, reading logs, or managing configuration files, Python makes it easy with built-in functions. This guide covers reading, writing, appending, and deleting files with practical examples.

Opening and Reading a File

# Read entire file

with open(‘data.txt’, ‘r’) as f:

    content = f.read()

    print(content)

# Read line by line

with open(‘data.txt’, ‘r’) as f:

    for line in f:

        print(line.strip())

Writing to a File

# Write (overwrites existing content)

with open(‘output.txt’, ‘w’) as f:

    f.write(‘Hello, World!\n’)

    f.write(‘Python file handling is easy.’)

# Append to file

with open(‘output.txt’, ‘a’) as f:

    f.write(‘\nThis line is appended.’)

Working with JSON Files

import json

# Write JSON

data = {‘name’: ‘Alice’, ‘age’: 25}

with open(‘data.json’, ‘w’) as f:

    json.dump(data, f)

# Read JSON

with open(‘data.json’, ‘r’) as f:

    loaded = json.load(f)

    print(loaded[‘name’])  # Alice

Deleting a File

import os

# Delete a file

if os.path.exists(‘output.txt’):

    os.remove(‘output.txt’)

    print(‘File deleted.’)

else:

    print(‘File not found.’)

Best Practices

Always use the ‘with’ statement (context manager) when working with files. It automatically closes the file even if an error occurs, preventing memory leaks and file corruption. Always check if a file exists before deleting or reading to avoid errors.

ConclusionThis guide covered “Python File Handling – Read, Write, Delete Files with Examples”. Bookmark this page and keep it as your go-to reference. If you found this helpful, share it with fellow developers and check out more snippets on programsnippet.com!

Leave a Reply

Your email address will not be published. Required fields are marked *