Python Tutorial
Estimated reading: 4 minutes 90 views

πŸ“‚ Python File Handling – Read, Write, and Manage Files


🧲 Introduction – Why File Handling Matters in Python?

File handling is an essential skill in Python for creating, reading, writing, updating, and deleting files. Whether you’re working on configuration files, logs, or data processing tasks, file I/O (Input/Output) operations are at the core of real-world Python applications.

🎯 In this guide, you’ll learn:

  • How to read, write, delete, and rename files
  • Methods for managing files and directories using the os and os.path modules
  • Common file-handling methods with real-life examples

πŸ“Œ Topics Covered

🧩 TopicπŸ“˜ Description
Python File Handling ExplainedOpening, reading, writing, and closing files
Python Read FilesHow to read files line-by-line or in chunks
Python Write/Create FilesWrite text or data to new or existing files
Python Delete FilesRemove unwanted files safely
Python Renaming and Deleting FilesRename and delete using the os module
Python File MethodsBuilt-in file object methods like read(), write(), close()
Python OS File/Directory MethodsManage files/folders with os functions
Python OS Path MethodsUse os.path to validate, join, and navigate paths

πŸ—‚οΈ Python File Handling Explained

To handle files, you typically use the built-in open() function.

file = open("example.txt", "r")
print(file.read())
file.close()

βœ… Modes:

  • 'r' – Read (default)
  • 'w' – Write (overwrite)
  • 'a' – Append
  • 'x' – Create
  • 'b' – Binary mode
  • 't' – Text mode (default)

Use a with block to auto-close files:

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

πŸ“– Python Read Files

πŸ”Ή Read Entire File

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

πŸ”Ή Read Line-by-Line

with open("sample.txt", "r") as f:
    for line in f:
        print(line)

πŸ”Ή Read Specific Lines

with open("sample.txt", "r") as f:
    print(f.readline())

✍️ Python Write/Create Files

πŸ”Ή Overwrite Existing or Create New File

with open("output.txt", "w") as f:
    f.write("This will overwrite the file.")

πŸ”Ή Append to a File

with open("output.txt", "a") as f:
    f.write("\nAppending new line.")

❌ Python Delete Files

import os

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

πŸ“ Python Renaming and Deleting Files

πŸ”Ή Rename a File

os.rename("old.txt", "new.txt")

πŸ”Ή Delete a Directory

os.rmdir("myfolder")

⚠️ Only works if the directory is empty.


🧰 Python File Methods

MethodDescription
read()Reads the entire file
readline()Reads one line
readlines()Returns a list of lines
write()Writes string to file
writelines()Writes list of strings
close()Closes the file

πŸ“ Python OS File/Directory Methods

MethodDescription
os.remove()Delete a file
os.rename()Rename a file or directory
os.rmdir()Remove an empty directory
os.mkdir()Create a new directory
os.listdir()List contents of a directory
os.getcwd()Get the current working directory
os.chdir(path)Change working directory

πŸ“‚ Python OS Path Methods

import os

print(os.path.exists("example.txt"))     # Check if file exists
print(os.path.isfile("example.txt"))     # Check if it's a file
print(os.path.isdir("myfolder"))         # Check if it's a directory
print(os.path.join("folder", "file.txt")) # Join paths

πŸ§ͺ Python File Handling Exercises

βœ… 1. Write and read from a file

with open("test.txt", "w") as f:
    f.write("Python file handling!")
with open("test.txt", "r") as f:
    print(f.read())

βœ… 2. Append and print all lines

with open("test.txt", "a") as f:
    f.write("\nAppended line.")
with open("test.txt") as f:
    for line in f:
        print(line.strip())

βœ… 3. Rename and delete file

os.rename("test.txt", "new_test.txt")
os.remove("new_test.txt")

πŸ“Œ Summary – Recap & Next Steps

Python’s file handling capabilities allow you to interact with the filesystem easily. From basic reading and writing to advanced OS-level file operations, mastering these tools empowers you to automate real-world tasks.

πŸ” Key Takeaways:

  • Use open() with modes (r, w, a, x) to manage files.
  • File objects offer methods like read(), write(), close().
  • Use os and os.path modules for advanced file/directory management.
  • Always close files, or use with statements for safety.

βš™οΈ Real-World Relevance:
Used in configuration management, logging, data pipelines, automation scripts, and backups.


❓ FAQ – Python File Handling


❓ What does the with open() syntax do?
βœ… It automatically handles opening and closing files, even if an error occurs.


❓ How do I check if a file exists?

import os
os.path.exists("filename.txt")

❓ What’s the difference between write() and writelines()?
βœ… write() adds a string; writelines() takes a list of strings.


❓ Can I delete a folder with files inside using os.rmdir()?
❌ No. Use shutil.rmtree() instead for non-empty folders.


❓ How to join paths safely across platforms?
βœ… Use os.path.join():

os.path.join("folder", "file.txt")

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ“‚ Python File Handling

Or Copy Link

CONTENTS
Scroll to Top