본문으로 건너뛰기
cccskills
무료GitHub에 공개

smart-file-writer

Diagnose file write failures by checking permissions, disk space, paths, and file locks. Get corrective steps before retrying, or check conditions before important writes to catch problems such as missing folders and read-only files.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

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.

연동 도구Excel

실행 점수 미검증

설치 방법 보기

이럴 때 유용합니다

  • Investigating permission errors when saving files
  • Checking disk space before saving large files
  • Resolving Windows path length problems
  • Handling files locked by another application

포함된 파일(8)

  • SKILL.md10.3 KB
  • QUALITY_CHECKLIST.md3.5 KB
  • README.md3.1 KB
  • references/diagnostic-procedures.md6.9 KB
  • references/index.md1.7 KB
  • references/integration-guide.md13.9 KB
  • references/platform-specific.md8.0 KB
  • scripts/validate.py5.3 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

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
  • Bypass security policies or antivirus software
  • Handle database write operations (different error domain)

Required inputs:

  • Target file path
  • Intended operation (write, append, create, etc.)
  • Error message (if reactive mode)

Quick Reference

Diagnostic Checklist (Run Before Retry)

1. Path Validation

import os
# Check path length (Windows: 260 char limit)
if len(filepath) > 260 and os.name == 'nt':
    print(f"Path too long: {len(filepath)} chars")

# Check parent directory exists
parent = os.path.dirname(filepath)
if not os.path.exists(parent):
    print(f"Parent directory missing: {parent}")

2. Permission Check

import os
# Check directory write permission
parent = os.path.dirname(filepath) or '.'
if not os.access(parent, os.W_OK):
    print(f"No write permission: {parent}")

# Check file permissions if exists
if os.path.exists(filepath):
    if not os.access(filepath, os.W_OK):
        print(f"File not writable: {filepath}")

3. Disk Space Check

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 100MB
    print(f"Low disk space: {free_gb:.2f} GB free")

4. File Lock Detection

import os
# Try to open with exclusive access
try:
    with open(filepath, 'a') as f:
        pass
except 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

def write_with_retry(filepath, content, max_retries=3):
    for attempt in range(max_retries):
        try:
            with open(filepath, 'w') as f:
                f.write(content)
            return True
        except (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

def shorten_path(long_path):
    """Use hash for long filenames"""
    dir_path = os.path.dirname(long_path)
    filename = os.path.basename(long_path)

    if len(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

Pattern 5: Permission Fix Suggestions

# Linux/Mac: Add write permission
chmod u+w filepath

# Windows: Remove read-only attribute
attrib -r filepath

# Windows: Take ownership (admin required)
takeown /f filepath
icacls filepath /grant %username%:F

Pattern 6: Detect Antivirus Interference

import time
import os

def is_antivirus_blocking(filepath):
    """Detect if antivirus is scanning file"""
    try:
        # Try to open exclusively
        with open(filepath, 'r+b') as f:
            pass
        return False
    except PermissionError:
        # Wait and retry
        time.sleep(0.5)
        try:
            with open(filepath, 'r+b') as f:
                pass
            return True  # Was temporarily blocked
        except:
            return False  # Persistent block

Proactive Pre-Write Validation

Before Any Critical Write

def validate_write_conditions(filepath):
    """Run before writing important files"""
    issues = []

    # 1. Path length
    if len(filepath) > 260 and os.name == 'nt':
        issues.append(f"Path too long: {len(filepath)} chars")

    # 2. Parent directory
    parent = os.path.dirname(filepath) or '.'
    if not os.path.exists(parent):
        issues.append(f"Parent missing: {parent}")
    elif not 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 writable
    if os.path.exists(filepath):
        if not 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 action
else:
    # Proceed with Write tool

Wrap Edit Tool

# Before editing, check file is writable
if not 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 output
if [ ! -w "$(dirname "$output_file")" ]; then
    echo "Cannot write to directory"
    exit 1
fi

Examples

Example 1: Reactive - Handle "Error writing file"

Input:

  • Error: "Error writing file: results/model_checkpoint.pth"
  • Operation: torch.save(model.state_dict(), filepath)

Steps:

  1. Run diagnostic checklist:
    • Path length: 45 chars ✓
    • Parent exists: No ✗
    • Permissions: N/A (parent missing)
    • Disk space: 50GB ✓
  2. Root cause: Parent directory doesn't exist
  3. Resolution: os.makedirs('results', exist_ok=True)
  4. Retry write operation
  5. Success

Expected output:

Diagnosis: Parent directory 'results' does not exist
Resolution: Created directory 'results'
Retry: torch.save() succeeded

Example 2: Proactive - Prevent Long Path Error

Input:

  • Target: D:\very\long\path\with\many\subdirectories\...\extremely_long_filename_that_exceeds_windows_limit.csv
  • Operation: pandas.to_csv()

Steps:

  1. Pre-write validation detects path length: 285 chars
  2. Suggest shortened path using hash
  3. Create mapping file for reference
  4. Write to shortened path
  5. Log original -> shortened mapping

Expected output:

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

Input:

  • Error: "PermissionError: [Errno 13] Permission denied: 'data.csv'"
  • Operation: Writing CSV file

Steps:

  1. Run diagnostic checklist:
    • File exists: Yes
    • File attributes: Read-only ✗
    • File lock: Not locked
    • Permissions: Read-only attribute set
  2. Root cause: File has read-only attribute
  3. Resolution: Suggest attrib -r data.csv
  4. After user confirms, remove attribute
  5. Retry write

Expected output:

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

Input:

  • Error: "PermissionError: [Errno 13] Permission denied: 'report.xlsx'"
  • Operation: Writing Excel file

Steps:

  1. Run diagnostic checklist:
    • File exists: Yes
    • Permissions: Writable
    • File lock test: Locked ✗
  2. Root cause: File open in Excel
  3. Resolution: Cannot proceed, inform user
  4. 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:

  1. Pre-write validation checks disk space
  2. Detects only 500MB free
  3. Warns before attempting write
  4. 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.

References

  • references/diagnostic-procedures.md: Detailed diagnostic workflows
  • references/platform-specific.md: Windows/Linux/Mac specific issues
  • references/integration-guide.md: Integrating with Claude Code tools
  • references/error-catalog.md: Common error messages and solutions

Maintenance

  • Sources: Python os/shutil docs, Windows file system limits, POSIX standards
  • Last updated: 2026-01-20
  • Known limits:
    • Network file systems (NFS/SMB) require specialized handling
    • Some antivirus software cannot be reliably detected
    • System-level permission changes require admin rights

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

adaptyv

무료

Support experimental validation of designed proteins through a cloud laboratory. Prepare and optimize sequences, submit tests for binding, expression, thermal stability, or enzyme activity, track experiment progress, and retrieve results through the API.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Submit designed proteins for binding tests
  • Request expression, thermal stability, or enzyme activity tests
  • Optimize sequences for solubility before experiments
foryourhealth111-pixel/Vibe-Skills3.8천2026년 10월 23일 업데이트

aeon

무료

Analyze time series, observations ordered over time, using aeon in Python. Build classification, prediction, and clustering workflows, detect unusual patterns or changes, and compare methods through an interface compatible with scikit-learn.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Classifying time series by their patterns
  • Forecasting future values from past observations
  • Detecting anomalies and change points
foryourhealth111-pixel/Vibe-Skills3.8천2026년 10월 23일 업데이트

Create original generative art with p5.js, using code to produce patterns and motion. Receive a written artistic concept and an interactive HTML viewer with adjustable parameters, reproducible random variations, seed navigation, and PNG downloads.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Create art from particle motion and flow fields
  • Explore patterns by adjusting sliders
  • Reproduce a favorite variation with the same seed
foryourhealth111-pixel/Vibe-Skills3.8천2026년 10월 23일 업데이트

Retrieve stock prices, exchange rates, cryptocurrency prices, company financial statements, and economic indicators through the Alpha Vantage API. It also covers historical data, news sentiment, and technical indicators, which summarize price and trading patterns.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Retrieve historical stock prices and trading volumes
  • Collect company financial statements and earnings data
  • Check foreign exchange and cryptocurrency prices
foryourhealth111-pixel/Vibe-Skills3.8천2026년 10월 23일 업데이트

Design backend systems with clear boundaries between business rules, databases, and external services. Use Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to organize new applications, refactor existing code, and make core logic easier to test.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Planning the structure of a new backend
  • Refactoring tightly coupled applications
  • Testing business rules independently of external services
foryourhealth111-pixel/Vibe-Skills3.8천2026년 10월 23일 업데이트

astropy

무료

Helps process astronomical data in Python by converting coordinates, units, and time scales, working with FITS observation files, matching object catalogs, and calculating distances using cosmological models.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Converting celestial coordinates
  • Reading and editing FITS observation files
  • Matching objects across astronomical catalogs
foryourhealth111-pixel/Vibe-Skills3.8천2026년 10월 23일 업데이트

foryourhealth111-pixel의 스킬 모두 보기

이 스킬의 문제 신고