Intelligent file write error handler: diagnoses permissions, disk space, path length, file locks before retrying. Use when you encounter 'Error writing file', 'Permission denied', 'Access denied', 'No space left', or related file write failures.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
Intelligent file write error handler: diagnoses permissions, disk space, path length, file locks before retrying. Use when you encounter 'Error writing file', 'Permission denied', 'Access denied', 'No space left', or related file write failures.
smart-file-writer Skill
Automatically diagnoses and resolves file write errors through systematic investigation rather than blind retries. Prevents common write failures proactively.
When to Use This Skill
Use this skill when any of these occurs:
"Error writing file" messages
"Permission denied" or "Access denied" errors
"No space left on device" errors
"File exists" conflicts
"Path too long" errors (Windows)
"Read-only file system" errors
Any file write operation failure (Python, CLI, any language)
Before critical file writes (proactive mode)
Not For / Boundaries
This skill does NOT:
Handle network file system issues (NFS, SMB) beyond basic diagnostics
Modify system-level permissions without user confirmation
import shutil
# Check available disk space
stat = shutil.disk_usage(os.path.dirname(filepath) or'.')
free_gb = stat.free / (1024**3)
if free_gb < 0.1: # Less than 100MBprint(f"Low disk space: {free_gb:.2f} GB free")
4. File Lock Detection
import os
# Try to open with exclusive accesstry:
withopen(filepath, 'a') as f:
passexcept PermissionError:
print(f"File locked by another process: {filepath}")
5. Windows-Specific Checks
# Check if file is in use (Windows)
handle.exe -a "filepath"# Check file attributes
attrib "filepath"
Resolution Patterns
Pattern 1: Create Missing Directories
import os
os.makedirs(os.path.dirname(filepath), exist_ok=True)
Pattern 2: Atomic Write (Temp + Rename)
import os
import tempfile
# Write to temp file first
temp_fd, temp_path = tempfile.mkstemp(dir=os.path.dirname(filepath))
try:
with os.fdopen(temp_fd, 'w') as f:
f.write(content)
# Atomic rename
os.replace(temp_path, filepath)
except Exception as e:
os.unlink(temp_path)
raise
Pattern 3: Exponential Backoff for Transient Issues
import time
defwrite_with_retry(filepath, content, max_retries=3):
for attempt inrange(max_retries):
try:
withopen(filepath, 'w') as f:
f.write(content)
returnTrueexcept (PermissionError, OSError) as e:
if attempt < max_retries - 1:
wait = 2 ** attempt # 1s, 2s, 4s
time.sleep(wait)
else:
raise
Pattern 4: Alternative Path (Shorten Long Paths)
import os
import hashlib
defshorten_path(long_path):
"""Use hash for long filenames"""
dir_path = os.path.dirname(long_path)
filename = os.path.basename(long_path)
iflen(long_path) > 260:
# Hash the filename
name, ext = os.path.splitext(filename)
hash_name = hashlib.md5(name.encode()).hexdigest()[:16]
return os.path.join(dir_path, f"{hash_name}{ext}")
return long_path
import time
import os
defis_antivirus_blocking(filepath):
"""Detect if antivirus is scanning file"""try:
# Try to open exclusivelywithopen(filepath, 'r+b') as f:
passreturnFalseexcept PermissionError:
# Wait and retry
time.sleep(0.5)
try:
withopen(filepath, 'r+b') as f:
passreturnTrue# Was temporarily blockedexcept:
returnFalse# Persistent block
Proactive Pre-Write Validation
Before Any Critical Write
defvalidate_write_conditions(filepath):
"""Run before writing important files"""
issues = []
# 1. Path lengthiflen(filepath) > 260and os.name == 'nt':
issues.append(f"Path too long: {len(filepath)} chars")
# 2. Parent directory
parent = os.path.dirname(filepath) or'.'ifnot os.path.exists(parent):
issues.append(f"Parent missing: {parent}")
elifnot os.access(parent, os.W_OK):
issues.append(f"No write permission: {parent}")
# 3. Disk space
stat = shutil.disk_usage(parent)
if stat.free < 100 * 1024 * 1024: # 100MB
issues.append(f"Low disk space: {stat.free / 1024**2:.1f} MB")
# 4. File exists and writableif os.path.exists(filepath):
ifnot os.access(filepath, os.W_OK):
issues.append(f"File not writable: {filepath}")
return issues
Integration with Claude Code Tools
Wrap Write Tool
# Before using Write tool, validate:
issues = validate_write_conditions(target_path)
if issues:
print("Pre-write validation failed:")
for issue in issues:
print(f" - {issue}")
# Take corrective actionelse:
# Proceed with Write tool
Wrap Edit Tool
# Before editing, check file is writableifnot os.access(filepath, os.W_OK):
print(f"Cannot edit: {filepath} is read-only")
# Suggest: chmod u+w or attrib -r
Wrap Bash File Operations
# Before redirecting outputif [ ! -w "$(dirname "$output_file")" ]; thenecho"Cannot write to directory"exit 1
fi
Warning: Path length 285 chars exceeds Windows limit (260)
Alternative: D:\very\long\path\...\a3f5e8b2c1d4.csv
Mapping saved to: path_mappings.json
Write succeeded to alternative path
Example 3: Reactive - Permission Denied on Windows
Diagnosis: File 'data.csv' has read-only attribute
Resolution: Run 'attrib -r data.csv' to remove read-only flag
[After user confirmation]
Attribute removed. Retry succeeded.
Example 4: Reactive - File Locked by Another Process
Suggest: Close Excel or write to alternative filename
Expected output:
Diagnosis: File 'report.xlsx' is locked by another process
Likely cause: File is open in Microsoft Excel
Resolution options:
1. Close Excel and retry
2. Write to alternative: 'report_new.xlsx'
3. Use atomic write with temp file
Cannot proceed automatically. User action required.
Example 5: Proactive - Low Disk Space
Input:
Target: Large model checkpoint (2GB)
Operation: torch.save()
Steps:
Pre-write validation checks disk space
Detects only 500MB free
Warns before attempting write
Suggests cleanup or alternative location
Expected output:
Warning: Insufficient disk space
Required: ~2.0 GB
Available: 0.5 GB
Recommendations:
1. Clean up temporary files
2. Write to alternative drive: E:\
3. Compress checkpoint before saving
Write operation blocked to prevent failure.