Back to all posts

File Handling(create, read, write, and delete files etc.)

File Handling in Python allows us to create, read, write, and delete files . It's an essential feature when working with data that needs to be stored perma…

File Handling in Python allows us to create, read, write, and delete files. It's an essential feature when working with data that needs to be stored permanently (like logs, configuration files, or reports).


🔹 Modes in File Handling

ModeDescription
'r'Read (default) – error if file doesn’t exist
'w'Write – creates a new file or overwrites existing one
'a'Append – creates a file if not exists, adds to the end
'x'Create – creates a new file, error if exists
'b'Binary mode (e.g., rb, wb)
't'Text mode (default, e.g., rt, wt)

✅ Basic Syntax

Python
file = open("filename.txt", "mode")
# do something with file
file.close()

📘 Examples

1. Writing to a File

Python
# 'w' creates or overwrites the file
file = open("sample.txt", "w")
file.write("Hello, this is Python file handling.\n")
file.write("Second line.")
file.close()

2. Reading from a File

Python
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close()

3. Appending to a File

Python
file = open("sample.txt", "a")
file.write("\nThis is appended text.")
file.close()

4. Reading Line by Line

Python
file = open("sample.txt", "r")
for line in file:
    print(line.strip())
file.close()

5. Using with (Best Practice)

Python
with open("sample.txt", "r") as file:
    print(file.read())

🔹 with automatically closes the file after the block.


🔍 Some Useful File Methods

PHP
file.read(size)       # Read 'size' characters
file.readline()       # Read a single line
file.readlines()      # Returns a list of lines
file.write(string)    # Write a string
file.seek(pos)        # Move to a certain byte in file
file.tell()           # Get current file position

📁 Deleting a File

To delete a file, use the os module:

Python
import os

if os.path.exists("sample.txt"):
    os.remove("sample.txt")
else:
    print("File does not exist.")

🔄 File Handling Real-World Example

Suppose you're logging user actions:

Python
def log_action(user, action):
    with open("user_log.txt", "a") as f:
        f.write(f"{user} performed {action}\n")

log_action("Alice", "Login")
log_action("Bob", "Logout")

Bilkul! Python mein file handling ke liye kuch important built-in libraries bhi hain jo kaafi useful hoti hain, especially jab aapko advanced file operations karne hote hain.


Python File Handling ke liye Important Libraries

1. os — Operating system ke functions ke liye

  • File delete karna, rename karna, folder create karna, etc.
Python
import os

# File delete karna
if os.path.exists("file.txt"):
    os.remove("file.txt")

# File rename karna
os.rename("oldname.txt", "newname.txt")

# Directory banani
os.mkdir("myfolder")

# Directory remove karni
os.rmdir("myfolder")

2. shutil — High-level file operations ke liye

  • File copy karna, move karna, directory copy karna
Python
import shutil

# File copy karna
shutil.copy("source.txt", "destination.txt")

# Directory copy karna
shutil.copytree("src_folder", "dst_folder")

# File move karna (rename ke tarah bhi kaam karta hai)
shutil.move("file.txt", "new_location/file.txt")

3. pathlib — Modern aur easy tarike se path aur file manage karne ke liye (Python 3.4+)

Python
from pathlib import Path

# File path banana
file_path = Path("folder") / "file.txt"

# File exists hai ya nahi check karna
if file_path.exists():
    print("File exists!")

# File create karna (agar nahi hai to)
file_path.touch()

# File delete karna
file_path.unlink()

# Directory create karna
dir_path = Path("myfolder")
dir_path.mkdir(exist_ok=True)

4. csv — CSV files ko read/write karne ke liye

Python
import csv

# CSV file write karna
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow()
    writer.writerow()
    writer.writerow()

# CSV file read karna
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

5. json — JSON files ke liye

Python
import json

# JSON data write karna
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
    json.dump(data, file)

# JSON data read karna
with open("data.json", "r") as file:
    data = json.load(file)
    print(data)

Summary:

LibraryUse Case
osFile/folder deletion, rename, etc.
shutilFile copy, move, directory copy
pathlibModern file & directory path handling
csvCSV file read/write
jsonJSON file read/write

Sure! चलिए pathlib के बारे में आसान और detail में समझते हैं।


Python की pathlib Library क्या है?

pathlib Python की एक modern library है जो file system paths को handle करने के लिए इस्तेमाल होती है।
यह traditional os.path से बेहतर और आसान है क्योंकि यह object-oriented style में काम करता है।


pathlib के फायदे:

  • Path को strings की जगह objects के रूप में treat करता है
  • Cross-platform support: Windows, Linux, MacOS सभी पर एक ही code चलेगा
  • File और directories के साथ काम करना आसान बनाता है

pathlib का Basic Use

Python
from pathlib import Path

# Path object बनाना (file या folder का path)
p = Path("folder") / "file.txt"

print(p)  # folder/file.txt (Linux/Mac)
          # folder\file.txt (Windows)

Common Operations with pathlib

1. File or Directory Exist करता है या नहीं

Bash
if p.exists():
    print("File ya folder exist karta hai")
else:
    print("File ya folder nahi mila")

2. File है या Directory

CSS
if p.is_file():
    print("Ye ek file hai")
elif p.is_dir():
    print("Ye ek directory hai")

3. File/Folder बनाना

Python
# Directory create karna (agar exist nahi karta ho to)
p_dir = Path("new_folder")
p_dir.mkdir(exist_ok=True)

# Empty file create karna
p_file = p_dir / "new_file.txt"
p_file.touch()

4. File Delete करना

CSS
if p_file.exists():
    p_file.unlink()
    print("File delete ho gaya")

5. File ka Parent Directory पता लगाना

Bash
print(p.parent)  # folder (parent directory ka path)

6. File ka naam, suffix, aur stem (naam bina extension ke)

Bash
print(p.name)     # file.txt
print(p.suffix)   # .txt
print(p.stem)     # file

Example: Directory ke andar files list karna

Bash
folder = Path("myfolder")

for file in folder.iterdir():
    print(file.name)

Example: File mein content read/write करना

Bash
file_path = Path("example.txt")

# Write (overwrite) karna
file_path.write_text("Hello from pathlib!")

# Read karna
content = file_path.read_text()
print(content)

Summary — pathlib से आप आसानी से कर सकते हैं:

  • Path create करना
  • Check करना कि file/folder exist करता है या नहीं
  • File/folder create, delete करना
  • File के नाम, extension को get करना
  • Directory के अंदर files list करना
  • File content read/write करना (text mode में)

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.