PyGuide

Learn Python with practical tutorials and code examples

Code Snippet Beginner
python• Updated Jan 15, 2024

Essential File Operations

Common file operations including reading, writing, and checking file existence

Essential File Operations

Read File Contents #

Read entire file #

# Method 1: Using with statement (recommended)
with open('file.txt', 'r') as f:
    content = f.read()
    print(content)

# Method 2: Using pathlib (modern approach)
from pathlib import Path
content = Path('file.txt').read_text()
print(content)

Read file line by line #

# Method 1: Iterate over file object
with open('file.txt', 'r') as f:
    for line in f:
        print(line.strip())  # strip() removes newline

# Method 2: Read all lines into list
with open('file.txt', 'r') as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())

# Method 3: Using pathlib
from pathlib import Path
lines = Path('file.txt').read_text().splitlines()
for line in lines:
    print(line)

Write to Files #

Write text to file #

# Overwrite existing file
with open('output.txt', 'w') as f:
    f.write('Hello, World!\n')
    f.write('Second line\n')

# Append to existing file
with open('output.txt', 'a') as f:
    f.write('Appended line\n')

# Using pathlib
from pathlib import Path
Path('output.txt').write_text('Hello, World!\n')

Write multiple lines #

lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']

# Method 1
with open('output.txt', 'w') as f:
    f.writelines(lines)

# Method 2
with open('output.txt', 'w') as f:
    for line in lines:
        f.write(line)

# Method 3: Join and write
content = ''.join(lines)
with open('output.txt', 'w') as f:
    f.write(content)

Check File/Directory Existence #

import os
from pathlib import Path

# Check if file exists
if os.path.exists('file.txt'):
    print('File exists')

# Using pathlib (recommended)
file_path = Path('file.txt')
if file_path.exists():
    print('File exists')

# Check if it's a file vs directory
if file_path.is_file():
    print('It is a file')
elif file_path.is_dir():
    print('It is a directory')

Get File Information #

import os
from pathlib import Path

file_path = Path('file.txt')

# File size
size = file_path.stat().st_size
print(f'File size: {size} bytes')

# Last modified time
import datetime
modified_time = datetime.datetime.fromtimestamp(file_path.stat().st_mtime)
print(f'Last modified: {modified_time}')

# File extension
extension = file_path.suffix
print(f'Extension: {extension}')

# File name without extension
name = file_path.stem
print(f'Name: {name}')

Create Directories #

import os
from pathlib import Path

# Create single directory
os.makedirs('new_directory', exist_ok=True)

# Using pathlib
Path('new_directory').mkdir(exist_ok=True)

# Create nested directories
Path('parent/child/grandchild').mkdir(parents=True, exist_ok=True)

List Directory Contents #

import os
from pathlib import Path

# List all items
for item in os.listdir('.'):
    print(item)

# Using pathlib
for item in Path('.').iterdir():
    print(item.name)

# List only files
for item in Path('.').iterdir():
    if item.is_file():
        print(item.name)

# List files with specific extension
for item in Path('.').glob('*.py'):
    print(item.name)

Copy and Move Files #

import shutil
from pathlib import Path

# Copy file
shutil.copy2('source.txt', 'destination.txt')

# Copy entire directory
shutil.copytree('source_dir', 'destination_dir')

# Move/rename file
shutil.move('old_name.txt', 'new_name.txt')

# Using pathlib for rename
Path('old_name.txt').rename('new_name.txt')

Delete Files and Directories #

import os
import shutil
from pathlib import Path

# Delete file
os.remove('file.txt')
# or
Path('file.txt').unlink()

# Delete empty directory
os.rmdir('empty_directory')
# or
Path('empty_directory').rmdir()

# Delete directory and all contents
shutil.rmtree('directory_with_contents')

Safe File Operations with Error Handling #

from pathlib import Path

def safe_read_file(file_path):
    """Safely read a file with error handling."""
    try:
        path = Path(file_path)
        if not path.exists():
            return None, "File does not exist"
        
        content = path.read_text(encoding='utf-8')
        return content, None
    except PermissionError:
        return None, "Permission denied"
    except UnicodeDecodeError:
        return None, "Cannot decode file"
    except Exception as e:
        return None, f"Error reading file: {e}"

# Usage
content, error = safe_read_file('file.txt')
if error:
    print(f"Error: {error}")
else:
    print(content)

Working with CSV Files #

import csv
from pathlib import Path

# Read CSV
def read_csv(file_path):
    with open(file_path, 'r', newline='') as f:
        reader = csv.DictReader(f)
        return list(reader)

# Write CSV
def write_csv(file_path, data, fieldnames):
    with open(file_path, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)

# Example usage
data = [
    {'name': 'Alice', 'age': 30},
    {'name': 'Bob', 'age': 25}
]
write_csv('people.csv', data, ['name', 'age'])

Working with JSON Files #

import json
from pathlib import Path

# Read JSON
def read_json(file_path):
    with open(file_path, 'r') as f:
        return json.load(f)

# Write JSON
def write_json(file_path, data):
    with open(file_path, 'w') as f:
        json.dump(data, f, indent=2)

# Example usage
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
write_json('person.json', data)
loaded_data = read_json('person.json')

Related Snippets

Snippet Beginner

Python For Loop Counter Code Examples

Ready-to-use Python code snippets for implementing for loops with counters using enumerate(), range(), and custom counter patterns.

#python #for-loop #counter +2
View Code
Syntax
Snippet Beginner

Python Dictionary Iteration Examples: Ready-to-Use Code

Ready-to-use Python code examples for iterating over dictionaries including keys, values, items, and advanced iteration patterns.

#python #dictionary #iteration +2
View Code
Data Structures
Snippet Beginner

Python Enumerate Start at 1: Code Examples and Snippets

Ready-to-use Python enumerate start at 1 code snippets for menus, lists, rankings, and user-friendly numbering systems.

#python #enumerate #start +2
View Code
Syntax
Snippet Beginner

Python For Loop Break: Ready-to-Use Code Examples

Copy-paste Python for loop break code snippets for search operations, early termination, and loop control in various scenarios.

#python #for-loop #break +2
View Code
Syntax