Index
File I/O in Python
Types of Files in Python
Opening, Reading, and Closing a File in Python
Writing a File in Python
Deleting a File in Python
1. File I/O in Python
Definition:
File Input/Output (I/O) in Python refers to the process of reading data from files and writing data to files. Python provides built-in functions and methods to handle file operations efficiently.
Use-Case Example:
File I/O is essential when you need to save data generated by a program, log outputs, or read input data from a file for processing.
Syntax:
# Opening a file
file = open("filename", "mode")
# Reading from a file
content = file.read()
# Writing to a file
file.write("data")
# Closing a file
file.close()
Rules:
Always close files after performing I/O operations to free system resources.
Handle exceptions to manage errors during file operations, such as file not found or permission denied.
Use different modes (
r
,w
,a
, etc.) based on the operation (reading, writing, appending).
Basic Example:
# Opening and reading a file
file = open("example.txt", "r")
content = file.read()
print(content) # Output: Content of example.txt
file.close()
2. Types of Files in Python
Definition:
Files in Python can be broadly categorized into two types: text files and binary files. Text files contain human-readable characters, while binary files contain data in a format not intended for human reading.
Use-Case Example:
Text files are used to store simple data like logs, configuration files, or CSV data. Binary files are used to store images, videos, and executable files.
Syntax:
# Example of opening different types of files
text_file = open("document.txt", "r")
binary_file = open("image.png", "rb")
Rules:
Text files are typically opened with modes like
r
,w
,a
, while binary files userb
,wb
,ab
.The content of binary files should be handled as bytes.
Basic Example:
# Reading a text file
text_file = open("example.txt", "r")
print(text_file.read()) # Output: Content of example.txt
text_file.close()
# Reading a binary file (example for context, not practical to print binary content)
binary_file = open("example.bin", "rb")
binary_content = binary_file.read()
print(binary_content) # Output: b'\x89PNG\r\n\x1a\n...'
binary_file.close()
3. Opening, Reading, and Closing a File in Python
Definition:
Opening a file in Python is the first step before performing any operation (reading or writing). After opening a file, you can read its content or write data to it. Once the operations are done, the file should be closed to free up system resources.
Use-Case Example:
Reading configuration data from a file to initialize program settings.
Syntax:
# Opening a file
file = open("filename", "mode")
# Reading from a file
content = file.read()
# Closing a file
file.close()
Rules:
Files must be opened in the correct mode based on the operation (
r
for reading,w
for writing,a
for appending).Always close files after operations to avoid resource leaks.
Basic Example:
# Opening and reading a file
file = open("example.txt", "r")
content = file.read()
print(content) # Output: Content of example.txt
file.close()
4. Writing a File in Python
Definition:
Writing to a file in Python involves opening the file in write (w
) or append (a
) mode and then writing data to it. If the file doesn’t exist, it is created.
Use-Case Example:
Saving user-generated data, such as form inputs or program outputs, to a text file.
Syntax:
# Opening a file in write mode
file = open("filename", "w")
# Writing to the file
file.write("data")
# Closing the file
file.close()
Rules:
Opening a file in
w
mode will overwrite the existing content. Usea
mode to append data.Ensure the file is properly closed after writing to save changes.
Basic Example:
# Writing to a file
file = open("output.txt", "w")
file.write("This is a sample text.")
file.close()
# Check the file content
file = open("output.txt", "r")
print(file.read()) # Output: This is a sample text.
file.close()
5. Deleting a File in Python
Definition:
Deleting a file in Python can be done using the os
module, which provides functions to interact with the operating system, including file deletion.
Use-Case Example:
Deleting temporary files or cleaning up after processing data files.
Syntax:
import os
# Deleting a file
os.remove("filename")
Rules:
Ensure the file exists before attempting to delete it to avoid errors.
Handle exceptions to manage situations where the file cannot be deleted (e.g., permission issues).
Basic Example:
import os
# Deleting a file
if os.path.exists("output.txt"):
os.remove("output.txt")
print("File deleted.")
else:
print("File does not exist.")
# Output: File deleted. (if the file existed)