<DataInsights />
  • 🏠 Home
  • 📊 SQL
  • 🐍 Python
  • 📈 Power BI
  • 📗 Excel
  • 💼 Career
  • 🎯 Interview Q&A
  • 📁 Case Study
  • 📥 Downloads
  • 🚀 My Portfolio
<DataInsights />

Practical Data Analytics tutorials covering SQL, Python, Power BI, Excel and career guidance for aspiring analysts — 100% free.

Topics

  • SQL Tutorials
  • Python Guide
  • Power BI
  • Excel Tips
  • Career Guide

Quick Links

  • 🛠️ All Tools
  • 🗓️ Archive
  • 📬 Contact
  • 🔍 Search
  • Portfolio
  • Kaggle
  • GitHub

Legal & Info

  • About
  • Contact
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • DMCA
  • Sitemap
Copyright © 2026 Data Insights by Jatin Kumar. All Rights Reserved.Built with ❤️ for Data Analysts
Home/error/Python FileNotFoundError — Complete Fix Guide...

Python FileNotFoundError — Complete Fix Guide

A
August 26, 2026 Jatin Kumar 19 min read error
Data Insights Errors Fix Guide

Python FileNotFoundError — Complete Fix Guide 📁

Python developers ka most common file error — FileNotFoundError. File nahi milti, wrong path, relative vs absolute confusion, permission issues — sab reasons cover karenge with solutions. Real employee CSV/Excel examples, debugging tips, aur interview questions ke saath. Data Insights par.

📑 Is Blog Mein Kya Sikhenge:

  • 🟢 Basic: FileNotFoundError kya hai, kab aati hai
  • 🟡 Medium: Common Causes — wrong path, typos, working directory
  • 🔴 Advanced: Relative vs Absolute paths, cross-platform issues
  • 🛠️ Solutions: os.path, pathlib, try-except handling
  • 🔍 Debugging: Kaise trace aur fix karo
  • 💬 Interview: Top asked questions

1. FileNotFoundError — Kya Hai? 🟢

📘 Definition: FileNotFoundError Python ka built-in exception hai jo tab raise hoti hai jab Python koi file open/read karne ki koshish karta hai but file specified path pe MILTI nahi. Ye OSError ki subclass hai (Python 3.3+). Beginners aur experienced developers dono ko face karni padti hai — file paths tricky hote hain, especially cross-platform work mein.

🎯 Samjho Hinglish Mein: Socho tumne friend ko bola "meri table pe rakhi employee.csv file lao". Friend gaya, table pe file nahi mili — return karke bola "file nahi mili". Yehi Python bhi karta hai! Tumne bola "employees.csv open karo" — Python ne dhundha, nahi mili — bola "FileNotFoundError". Reasons: file exist hi nahi karti, wrong location mein hai, wrong spelling di, wrong extension likha, ya current directory galat hai. Data analysis mein daily face karte hain — CSV, Excel, JSON files load karte time.

📊 Sample Data (Employee CSV):

# File: employees.csv (in project folder)
# id,name,department,salary
# 101,Aarav,IT,55000
# 102,Ishita,HR,72000
# 103,Kabir,Finance,65000
# 104,Diya,IT,58000
# 105,Rohan,Marketing,80000

# Try to open the file
with open("employees.csv") as f:
    data = f.read()
print(data)
# ✅ Works IF file exists in current directory
# ❌ FileNotFoundError otherwise

❌ Error Output:

with open("employees.csv") as f:
    data = f.read()

# ❌ ERROR OUTPUT:
# Traceback (most recent call last):
#   File "load_data.py", line 1, in <module>
#     with open("employees.csv") as f:
# FileNotFoundError: [Errno 2] No such file or directory: 'employees.csv'
⚡ Common FileNotFoundError Situations:
• File doesn't exist — never created ya deleted
• Wrong filename — typo, extension missing
• Wrong path — file in different folder
• Wrong working directory — script running from unexpected location
• Case sensitivity — Linux/Mac case-sensitive, Windows nahi
• Permission denied — different error (PermissionError)

2. Cause 1 — File Doesn't Exist 🟡

📘 Cause: Sabse simple case — file exist hi nahi karti. Maybe delete ho gayi, kabhi banayi nahi, ya wrong folder mein search kar rahe ho. Beginner mistake — assume karte hain file wahan hogi jahan expect kar rahe.

❌ Wrong Code (Error):

# ❌ File doesn't exist
with open("employees.csv") as f:
    data = f.read()
# FileNotFoundError: No such file or directory: 'employees.csv'

# ❌ File was deleted
import os
os.remove("employees.csv")
with open("employees.csv") as f:   # File was just deleted
    data = f.read()
# FileNotFoundError

# ❌ Assuming file created but wasn't
import pandas as pd
df = pd.read_csv("employee_data.csv")   # Wrong name!
# Actual file: employees.csv

✅ Fix — Check Before Opening:

# ✅ Solution 1: Check if file exists (os module)
import os

if os.path.exists("employees.csv"):
    with open("employees.csv") as f:
        data = f.read()
    print("✅ File loaded successfully")
else:
    print("❌ File not found. Please check path.")

# ✅ Solution 2: os.path.isfile() (more specific)
if os.path.isfile("employees.csv"):
    with open("employees.csv") as f:
        data = f.read()

# ✅ Solution 3: pathlib (modern approach)
from pathlib import Path

file_path = Path("employees.csv")
if file_path.exists():
    with open(file_path) as f:
        data = f.read()
    print("✅ File loaded")
else:
    print(f"❌ {file_path} not found")

# ✅ Solution 4: Create file if missing
import os

if not os.path.exists("employees.csv"):
    # Create sample file with headers
    with open("employees.csv", "w") as f:
        f.write("id,name,department,salary\n")
        f.write("101,Aarav,IT,55000\n")
        f.write("102,Ishita,HR,72000\n")
    print("✅ Sample file created")

with open("employees.csv") as f:
    data = f.read()
print(data)

3. Cause 2 — Wrong Path/Location 🟡

📘 Cause: File exist karti hai but tum WRONG PATH de rahe ho. Relative path use kiya but current directory different hai, ya absolute path galat hai. Ye sabse frustrating error hai — file sirf 2 folders door hai but Python nahi dhund pa raha.

❌ Wrong Code (Error):

# Project structure:
# project/
#   ├── scripts/
#   │   └── analyze.py
#   └── data/
#       └── employees.csv

# ❌ Wrong: Running analyze.py from scripts/ folder
with open("employees.csv") as f:
    data = f.read()
# FileNotFoundError: file is in ../data/, not current dir

# ❌ Wrong: Assuming path is absolute
with open("data/employees.csv") as f:
    data = f.read()
# Works only if run from project/ folder
# Fails if run from anywhere else!

# ❌ Wrong: Windows path with single backslash
with open("C:\Users\aarav\employees.csv") as f:
    data = f.read()
# SyntaxError or wrong path (\ is escape character)

✅ Fix — Use Correct Paths:

# ✅ Solution 1: Use relative path with ..
with open("../data/employees.csv") as f:
    data = f.read()
# ✅ Go up one level, then into data/

# ✅ Solution 2: Absolute path (Windows — use raw string)
with open(r"C:\Users\aarav\project\data\employees.csv") as f:
    data = f.read()
# 'r' prefix = raw string (no escape characters)

# ✅ Solution 3: Absolute path (Windows — forward slashes)
with open("C:/Users/aarav/project/data/employees.csv") as f:
    data = f.read()
# Forward slashes work on Windows too!

# ✅ Solution 4: Path relative to script location (BEST!)
import os

script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, "..", "data", "employees.csv")

with open(file_path) as f:
    data = f.read()
# ✅ Works regardless of where you run script from!

# ✅ Solution 5: Modern pathlib (RECOMMENDED)
from pathlib import Path

script_dir = Path(__file__).parent
file_path = script_dir / ".." / "data" / "employees.csv"

with open(file_path) as f:
    data = f.read()
# ✅ Cross-platform, clean syntax!

# ✅ Solution 6: Check current working directory
import os
print("Current directory:", os.getcwd())
# Helps debug where Python is looking

4. Cause 3 — Relative vs Absolute Path Confusion 🔴

📘 Definition: Relative path current working directory se relative hoti hai (e.g., data/file.csv). Absolute path full path hoti hai root se (e.g., C:/Users/.../file.csv). Confusion tab hoti hai jab script kahin aur se run hoti hai — relative paths break ho jaate hain.

📋 Relative vs Absolute Comparison:

TypeExampleProsCons
Relativedata/emp.csvShort, portableDepends on CWD
AbsoluteC:/Users/.../emp.csvAlways worksNot portable
Script-relativePath(__file__).parent / "data"Best of bothSlightly complex

💻 Path Handling Examples:

# Project structure:
# /home/aarav/project/
#     ├── scripts/
#     │   └── main.py
#     └── data/
#         └── employees.csv

import os
from pathlib import Path

# RELATIVE PATHS — depend on current directory

# If running from project/ folder
with open("data/employees.csv") as f: # ✅ Works
    data = f.read()

# If running from scripts/ folder
with open("../data/employees.csv") as f: # ✅ Go up one
    data = f.read()

# If running from /home/aarav/ folder
with open("project/data/employees.csv") as f: # ✅
    data = f.read()


# ABSOLUTE PATHS — always work but not portable

# Linux/Mac
with open("/home/aarav/project/data/employees.csv") as f:
    data = f.read()

# Windows — 3 ways
with open(r"C:\Users\aarav\project\data\employees.csv") as f:
    data = f.read()   # Raw string ✅

with open("C:/Users/aarav/project/data/employees.csv") as f:
    data = f.read()   # Forward slashes ✅

with open("C:\\Users\\aarav\\project\\data\\employees.csv") as f:
    data = f.read()   # Escaped backslashes ✅


# SCRIPT-RELATIVE PATHS (BEST APPROACH!)

# Using os.path
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, "..", "data", "employees.csv")

# Using pathlib (modern, recommended)
script_dir = Path(__file__).parent
file_path = script_dir.parent / "data" / "employees.csv"

# Both work regardless of where script is run from!
with open(file_path) as f:
    data = f.read()
print("✅ Data loaded successfully")
🎯 Path Notation Reference:
• . — current directory
• .. — parent directory (one level up)
• ../.. — two levels up
• ~ — home directory (Linux/Mac)
• / — root directory (Linux/Mac) or drive separator (Windows)
• \ — path separator on Windows (needs escaping: \\ ya raw string r"...")

5. Modern Solution — pathlib Module 🔴

📘 Definition: pathlib Python 3.4+ ka modern module hai for handling file paths — object-oriented approach. Cross-platform (Windows/Linux/Mac same code), cleaner syntax, powerful methods. Modern Python code mein pathlib use karna standard hai — old os.path se better.

💻 pathlib Complete Guide:

from pathlib import Path

# Create Path objects
file_path = Path("employees.csv")
data_dir = Path("data")

# Combine paths with / operator (cleaner than os.path.join!)
full_path = data_dir / "employees.csv"
# Result: data/employees.csv (or data\employees.csv on Windows)

# Check if file exists
if file_path.exists():
    print("✅ File exists")

if file_path.is_file():
    print("✅ Is a file")

if data_dir.is_dir():
    print("✅ Is a directory")

# Get file properties
print(file_path.name)         # employees.csv
print(file_path.stem)         # employees (no extension)
print(file_path.suffix)       # .csv
print(file_path.parent)       # . (parent directory)
print(file_path.absolute())   # Full absolute path

# Path relative to script
script_dir = Path(__file__).parent
data_file = script_dir / "data" / "employees.csv"

# Home directory
home = Path.home()   # /home/user or C:\Users\user
config_file = home / ".config" / "app.json"

# Current working directory
cwd = Path.cwd()
print(f"Working in: {cwd}")

# Iterate over files in directory
for file in data_dir.iterdir():
    print(file.name)

# Find all CSV files
for csv_file in data_dir.glob("*.csv"):
    print(csv_file)

# Recursive search — all CSV files in all subdirectories
for csv_file in data_dir.rglob("*.csv"):
    print(csv_file)

# Read file directly with pathlib
content = file_path.read_text()   # Text file
data = file_path.read_bytes()      # Binary file

# Write file with pathlib
file_path.write_text("id,name\n101,Aarav")

# Create directory (if not exists)
data_dir.mkdir(exist_ok=True)
Path("data/backups").mkdir(parents=True, exist_ok=True)

# Delete file safely
if file_path.exists():
    file_path.unlink()   # Delete file

📋 os.path vs pathlib Comparison:

Taskos.path (old)pathlib (modern)
Join pathsos.path.join("a", "b")Path("a") / "b"
Check existsos.path.exists(path)path.exists()
Get filenameos.path.basename(path)path.name
Get extensionos.path.splitext(path)[1]path.suffix
Home directoryos.path.expanduser("~")Path.home()
Current directoryos.getcwd()Path.cwd()

6. Try-Except Handling 🛠️

📘 Definition: Try-except block use karke FileNotFoundError ko gracefully handle karo — program crash nahi hoga, user-friendly message dega. Ye "EAFP" (Easier to Ask Forgiveness than Permission) Pythonic approach hai — try file open karo, error aaye toh handle karo.

💻 Try-Except Patterns:

# ✅ Pattern 1: Basic try-except
try:
    with open("employees.csv") as f:
        data = f.read()
    print("✅ File loaded")
except FileNotFoundError:
    print("❌ File not found")
    data = None

# ✅ Pattern 2: With error message details
try:
    with open("employees.csv") as f:
        data = f.read()
except FileNotFoundError as e:
    print(f"❌ Error: {e}")
    print(f"File name: {e.filename}")

# ✅ Pattern 3: Multiple exceptions
try:
    with open("employees.csv") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found")
except PermissionError:
    print("No permission to read file")
except IsADirectoryError:
    print("That's a directory, not a file")
except Exception as e:
    print(f"Unexpected error: {e}")

# ✅ Pattern 4: With fallback file
try:
    with open("employees.csv") as f:
        data = f.read()
except FileNotFoundError:
    print("Main file missing, using backup")
    with open("employees_backup.csv") as f:
        data = f.read()

# ✅ Pattern 5: Reusable safe function
def safe_read_file(filepath, default=""):
    """Safely read a file, return default if not found"""
    try:
        with open(filepath) as f:
            return f.read()
    except FileNotFoundError:
        print(f"⚠️ {filepath} not found, using default")
        return default
    except Exception as e:
        print(f"❌ Error reading {filepath}: {e}")
        return default

# Usage
data = safe_read_file("employees.csv")

# ✅ Pattern 6: Pandas with error handling
import pandas as pd

def load_employees(filepath):
    try:
        df = pd.read_csv(filepath)
        print(f"✅ Loaded {len(df)} employees")
        return df
    except FileNotFoundError:
        print(f"❌ {filepath} not found")
        return pd.DataFrame()   # Empty DataFrame
    except pd.errors.EmptyDataError:
        print("❌ File is empty")
        return pd.DataFrame()

df = load_employees("employees.csv")

7. Real-World Scenarios 💼

💼 Scenario 1: Loading Employee CSV

import pandas as pd
from pathlib import Path

# Robust employee data loader
def load_employee_data(filename="employees.csv"):
    # Try multiple locations
    possible_paths = [
        Path(filename),                              # Current dir
        Path("data") / filename,                    # data/ subdir
        Path(__file__).parent / filename,           # Script dir
        Path(__file__).parent / "data" / filename, # Script/data
        Path.home() / "Documents" / filename,     # Documents
    ]
    
    for path in possible_paths:
        if path.exists():
            print(f"✅ Found at: {path}")
            return pd.read_csv(path)
    
    raise FileNotFoundError(
        f"❌ {filename} not found in any location"
    )

# Usage
try:
    df = load_employee_data()
    print(df.head())
except FileNotFoundError as e:
    print(e)

💼 Scenario 2: Config File Loading

import json
from pathlib import Path

def load_config(config_file="config.json"):
    # Default configuration
    default_config = {
        "data_dir": "data",
        "output_dir": "output",
        "log_level": "INFO"
    }
    
    config_path = Path(config_file)
    
    if not config_path.exists():
        print(f"⚠️ {config_file} not found. Creating default.")
        with open(config_path, "w") as f:
            json.dump(default_config, f, indent=2)
        return default_config
    
    try:
        with open(config_path) as f:
            return json.load(f)
    except Exception as e:
        print(f"❌ Config error: {e}. Using defaults")
        return default_config

config = load_config()
print(config)

💼 Scenario 3: Batch File Processing

import pandas as pd
from pathlib import Path

# Process multiple employee files
def process_all_files(directory="data"):
    data_dir = Path(directory)
    
    if not data_dir.exists():
        print(f"❌ Directory {directory} not found")
        return []
    
    results = []
    csv_files = list(data_dir.glob("employee_*.csv"))
    
    if not csv_files:
        print(f"⚠️ No employee_*.csv files in {directory}")
        return []
    
    for file in csv_files:
        try:
            df = pd.read_csv(file)
            results.append({
                "file": file.name,
                "rows": len(df),
                "total_salary": df["salary"].sum()
            })
            print(f"✅ Processed {file.name}")
        except FileNotFoundError:
            print(f"❌ {file.name} disappeared")
        except Exception as e:
            print(f"❌ Error in {file.name}: {e}")
    
    return results

# Usage
summary = process_all_files()
for item in summary:
    print(item)

8. Debugging Tips 🔍

📋 Debugging Checklist:

StepCheckCommand
1Current working directoryos.getcwd()
2File exists checkPath(file).exists()
3List directory contentsos.listdir(".")
4Get absolute pathPath(file).absolute()
5Check file spelling/caseManual verification
6Verify extension.csv vs .CSV vs .txt

🔍 Debugging Techniques:

import os
from pathlib import Path

# Technique 1: Print current directory
print("Current directory:", os.getcwd())
print("Script location:", Path(__file__).parent)

# Technique 2: List all files in current directory
for item in Path(".").iterdir():
    if item.is_file():
        print(f"📄 {item.name}")
    elif item.is_dir():
        print(f"📁 {item.name}/")

# Technique 3: Verify file details
file = Path("employees.csv")
print(f"File: {file.name}")
print(f"Exists: {file.exists()}")
print(f"Absolute: {file.absolute()}")
print(f"Parent: {file.parent}")
print(f"Is file: {file.is_file()}")

# Technique 4: Search for file recursively
for match in Path(".").rglob("employees.csv"):
    print(f"Found: {match.absolute()}")

# Technique 5: Debug function
def debug_file_access(filepath):
    print(f"\n=== Debug: {filepath} ===")
    print(f"Current dir: {os.getcwd()}")
    
    path = Path(filepath)
    print(f"File path: {path}")
    print(f"Absolute: {path.absolute()}")
    print(f"Exists: {path.exists()}")
    print(f"Parent exists: {path.parent.exists()}")
    
    if path.parent.exists():
        print(f"Files in {path.parent}:")
        for f in path.parent.iterdir():
            print(f"  - {f.name}")

# Usage
debug_file_access("data/employees.csv")

9. Interview Questions 💬

Q1: FileNotFoundError kya hai aur kab aati hai?
Ans: FileNotFoundError Python ki built-in exception hai jo tab raise hoti hai jab Python koi file open ya access karne ki koshish karta hai but file specified path pe nahi milti. Ye OSError ki subclass hai (Python 3.3+). Common causes: (1) File doesn't exist. (2) Wrong file path. (3) Wrong current working directory. (4) Typo in filename. (5) Case sensitivity issues (Linux/Mac). (6) Missing extension. Prevention: check with os.path.exists() or Path.exists() before opening, use try-except for graceful handling. Real-world: data loading, config files, log files — sab jagah aati hai.

Q2: Relative path aur absolute path mein kya difference hai?
Ans: Relative path current working directory (CWD) se relative hoti hai — data/emp.csv means "look in data folder inside CWD". Absolute path full path root se — /home/user/project/data/emp.csv — always same regardless of CWD. Trade-offs: (1) Relative paths PORTABLE (project move kar sakte ho) but CWD-dependent. (2) Absolute paths ALWAYS WORK but system-specific. Best practice: script-relative paths use karo — Path(__file__).parent / "data" / "file.csv" — script location se relative, portable + reliable. Modern Python: pathlib module use karo, cross-platform code likhne ke liye.

Q3: pathlib aur os.path mein kya difference hai?
Ans: os.path — old procedural API, string-based paths. pathlib — modern object-oriented API (Python 3.4+), cleaner syntax. Key differences: (1) Syntax — pathlib uses / operator: Path("a") / "b". os.path uses functions: os.path.join("a", "b"). (2) Objects — pathlib returns Path objects, os.path returns strings. (3) Methods — pathlib has built-in methods (path.exists()), os.path uses separate functions. (4) Cross-platform — pathlib handles Windows/Linux paths automatically. (5) Readability — pathlib more Pythonic. Modern preference: pathlib for new code, os.path for legacy compatibility. Best practice: mix both if needed (they interoperate well).

Q4: Windows mein file paths kaise handle karo?
Ans: Windows uses \ (backslash) as path separator, but Python treats \ as escape character. 3 solutions: (1) Raw strings — prefix with r: r"C:\Users\file.txt" — most common. (2) Forward slashes — Python accepts forward slashes on Windows too: "C:/Users/file.txt". (3) Escaped backslashes — "C:\\Users\\file.txt" — verbose. (4) pathlib — automatic handling: Path("C:/Users") / "file.txt". Best practice: use forward slashes ya pathlib for cross-platform code. Never use raw backslashes without raw string prefix — SyntaxError ya wrong paths.

Q5: File exists check karne ke different tarike kya hain?
Ans: Multiple approaches: (1) os.path.exists() — file ya folder dono check karta hai — os.path.exists("file.csv"). (2) os.path.isfile() — sirf files check karta hai (folders skip). (3) os.path.isdir() — sirf folders. (4) pathlib.Path.exists() — modern approach: Path("file.csv").exists(). (5) pathlib.Path.is_file() — specifically files. (6) Try-except — try file open, catch FileNotFoundError. Best practice depends on scenario: Check + open — race condition possible (file deleted between check and open). Try-except — Pythonic EAFP style, atomic operation. Modern code: try-except preferred for robustness.

Q6: Script kahin se bhi run ho, file path kaise reliable banao?
Ans: Script-relative paths use karo — script ke location se relative, not CWD. Two approaches: (1) os.path: script_dir = os.path.dirname(os.path.abspath(__file__)), then os.path.join(script_dir, "data", "file.csv"). (2) pathlib (modern): script_dir = Path(__file__).parent, then script_dir / "data" / "file.csv". Kaise kaam karta hai: __file__ always current script ka path deta hai. Uska parent = script's folder. Us folder se relative path build karo. Fayda: script kahin se bhi run karo, paths always correct. Interview mein yeh technique batao — production-ready code dikhata hai.

Q7: FileNotFoundError vs OSError vs IOError — kya farak hai?
Ans: Exception hierarchy samjhne se clarity aayegi: (1) OSError — parent class for all OS-related errors (Python 3.3+ unified). (2) FileNotFoundError — OSError ki subclass, specifically file/directory not found. (3) IOError — Python 3 mein alias for OSError (Python 2 mein separate tha). Related subclasses: PermissionError (no access), IsADirectoryError (expected file, got directory), NotADirectoryError (expected directory, got file), FileExistsError (file already exists during create). Best practice: catch specific — except FileNotFoundError:. Broader: except OSError: catches all. Interview mein OSError hierarchy pata hona chahiye.

Q8: Production mein FileNotFoundError kaise prevent karte hain?
Ans: Multi-layered defense: (1) Configuration files — file paths hardcode nahi, config se load karo. (2) Environment variables — production paths env vars mein rakho. (3) Try-except with logging — errors log karo Sentry/DataDog. (4) Fallback files — primary missing toh backup use karo. (5) Health checks — startup mein critical files verify karo. (6) Docker volumes — files consistent locations pe mount karo. (7) File validation — deployment ke pehle files ki existence check. (8) Error monitoring — production mein FileNotFoundError alerts setup. (9) Graceful degradation — missing file ke case mein defaults use karo. (10) Documentation — required files clearly document karo README mein. Real production: use container orchestration (Kubernetes) with proper volume mounts, monitoring for file-related errors.

10. Quick Cheat Sheet 📋

# ══════════════════════════════════════
# COMMON CAUSES
# ══════════════════════════════════════

# 1. File doesn't exist
open("missing.csv")   # ❌ Error!

# 2. Wrong path/location
open("data/emp.csv")   # Depends on CWD

# 3. Windows backslash issue
open("C:\Users\file")   # ❌ Escape chars!

# 4. Case sensitivity (Linux/Mac)
open("Employees.csv")   # ≠ employees.csv


# ══════════════════════════════════════
# SOLUTIONS
# ══════════════════════════════════════

# Solution 1: Check exists (os)
import os
if os.path.exists("file.csv"):
    with open("file.csv") as f:
        data = f.read()

# Solution 2: Check exists (pathlib)
from pathlib import Path
if Path("file.csv").exists():
    with open("file.csv") as f:
        data = f.read()

# Solution 3: Try-except (Pythonic)
try:
    with open("file.csv") as f:
        data = f.read()
except FileNotFoundError:
    print("File not found")
    data = None


# ══════════════════════════════════════
# PATH HANDLING
# ══════════════════════════════════════

# Windows — 3 correct ways
open(r"C:\Users\file.csv")     # Raw string
open("C:/Users/file.csv")      # Forward slash
open("C:\\Users\\file.csv")    # Escaped

# Script-relative path (BEST!)
from pathlib import Path
script_dir = Path(__file__).parent
file_path = script_dir / "data" / "file.csv"


# ══════════════════════════════════════
# PATHLIB COMMON OPERATIONS
# ══════════════════════════════════════

from pathlib import Path

path = Path("data/employees.csv")

path.exists()          # True/False
path.is_file()         # True/False
path.is_dir()          # True/False
path.name              # employees.csv
path.stem              # employees
path.suffix            # .csv
path.parent            # data/
path.absolute()        # Full path
path.read_text()       # Read file
path.write_text("data")  # Write file


# ══════════════════════════════════════
# DEBUGGING
# ══════════════════════════════════════

import os
print(os.getcwd())          # Current directory
print(os.listdir("."))       # Files in current dir

from pathlib import Path
Path.cwd()                 # Current directory
list(Path(".").iterdir())    # List contents


# ══════════════════════════════════════
# GOLDEN RULES
# ══════════════════════════════════════
# 1. Use pathlib for modern code
# 2. Script-relative paths for portability
# 3. Try-except for robust error handling
# 4. Forward slashes work on all OS
# 5. Raw strings for Windows paths (r"...")
# 6. Verify file exists before opening
# 7. Print os.getcwd() when debugging
# 8. Provide meaningful error messages
📋 Final Summary:
• 📁 FileNotFoundError = Python can't find the file
• 🔍 Check os.getcwd() first — CWD often the culprit
• ✅ Use Path.exists() before opening
• 🎯 pathlib is modern, cross-platform, cleaner
• 💡 Script-relative paths: Path(__file__).parent
• 🛡️ Try-except for graceful error handling
• 🪟 Windows: use raw strings r"..." or forward slashes
• 💼 Production: config-based paths, health checks, monitoring

Next: Data Insights Errors Fix Guide

Agle blog mein hum cover karenge: Python UnboundLocalError — Complete Fix Guide. Variable scope issues, local vs global variables, kaise scope confusion se bachein, real-world scenarios employee data ke saath. Errors series continues — RecursionError aur Pandas errors sab upcoming. Data Insights par!

Happy Debugging & Keep Coding! 🚀

👤
Jatin Kumar
Data Analyst & Educator

Python, SQL, Power BI aur Excel mein practical tutorials likhta hoon — taaki data analytics seekhna aasan ho. Portfolio: jatinanalytics.co.in

Portfolio LinkedIn GitHub Kaggle All Articles
Share:

💬 Comments (0)

Spam/links allowed nahi hain — respectful comments welcome!

Loading comments...

Was this article helpful?