Tuesday, August 26, 2025

๐ŸFILE HANDLING AND OS INTERACTION IN PYTHON

Python allows you to read, write, and manipulate files, as well as interact with your operating system.

1) Why File Handling and OS Interaction?

File handling is essential to save and retrieve data persistently. OS interaction allows Python programs to communicate with the system for tasks like checking directories, listing files, or running commands.

2) File Handling Basics

Python provides the built-in open() function to work with files.


# Open a file in write mode
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("Python is amazing!")
file.close()

# Open a file in read mode
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

Modes:

  • "r" – Read (default)
  • "w" – Write (overwrite)
  • "a" – Append
  • "r+" – Read & Write
  • "b" – Binary mode (e.g., "rb")

3) Using with Statement

Automatically closes the file after the block, reducing errors.


with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# File is automatically closed here

4) Reading Lines from a File


with open("example.txt", "r") as file:
    # Read line by line
    for line in file:
        print(line.strip())

    # Read all lines into a list
    file.seek(0)
    lines = file.readlines()
    print(lines)

5) Writing Multiple Lines


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

with open("example.txt", "w") as file:
    file.writelines(lines)

6) Interacting with the Operating System

Python’s os module allows you to work with directories and files.


import os

# Current working directory
print(os.getcwd())

# List files and directories
print(os.listdir())

# Create a directory
os.mkdir("new_folder")

# Rename a file
os.rename("example.txt", "example_renamed.txt")

# Delete a file
os.remove("example_renamed.txt")

# Remove a directory
os.rmdir("new_folder")

7) Common Mistakes

  • Forgetting to close files (use with to avoid this)
  • Opening a non-existent file in read mode → FileNotFoundError
  • Trying to remove non-empty directories → OSError
  • Confusing relative and absolute paths

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??