File handling in Python allows reading, writing, and managing files efficiently. Python provides built-in functions for working with text and binary files.
Python uses the open() function to handle files.
file = open("example.txt", "r") # Opens a file in read mode
file.close() # Always close the file after use| Mode | Description |
|---|---|
"r" | Read (default), file must exist |
"w" | Write, creates a new file or overwrites existing content |
"a" | Append, adds data to an existing file |
"x" | Create, fails if file already exists |
"rb" | Read binary mode |
"wb" | Write binary mode |
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open()ensures the file is closed automatically.
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Removes newline characterswith open("example.txt", "r") as file:
print(file.read(10)) # Reads first 10 characterswith open("example.txt", "r") as file:
lines = file.readlines() # Reads all lines into a list
print(lines)with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python File Handling Tutorial")
"w"mode overwrites existing content.
with open("example.txt", "a") as file:
file.write("\nAppending new content!")Binary files store data like images, videos, and executables.
with open("image.png", "rb") as file:
data = file.read()
print(data[:10]) # Display first 10 byteswith open("copy.png", "wb") as file:
file.write(data)import os
if os.path.exists("example.txt"):
print("File exists!")
else:
print("File not found!")Use open("filename", "mode") to work with files.
Always close files or use with open() for automatic closing. "r" to read, "w" to write, "a" to append, and "x" to create new files.
Handle text and binary files separately.
Sign in to join the discussion and post comments.
Sign inPython for Web Development
Python for Web Development is a comprehensive tutorial series covering the fundamentals of building web applications using Flask and Django. From setting up a project to working with databases, authentication, REST APIs, and deployment on cloud platforms, this series provides a solid foundation for developing secure and scalable web applications.
Object-Oriented Programming (OOP) in Python
Learn the fundamentals of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and more. Understand how OOP enhances code reusability, scalability, and organization.