π 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
osandos.pathmodules - Common file-handling methods with real-life examples
π Topics Covered
| π§© Topic | π Description |
|---|---|
| Python File Handling Explained | Opening, reading, writing, and closing files |
| Python Read Files | How to read files line-by-line or in chunks |
| Python Write/Create Files | Write text or data to new or existing files |
| Python Delete Files | Remove unwanted files safely |
| Python Renaming and Deleting Files | Rename and delete using the os module |
| Python File Methods | Built-in file object methods like read(), write(), close() |
| Python OS File/Directory Methods | Manage files/folders with os functions |
| Python OS Path Methods | Use 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
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
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
osandos.pathmodules for advanced file/directory management. - Always close files, or use
withstatements 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 :
