Unit Iv-1
Unit Iv-1
File in Python
A file is a collection of data or information stored on a storage device, which can be textual or binary.
Python treats files as objects and allows interaction with them through file handling methods.
1. Text Files
2. Binary Files
1. Text Files
Text files store data in human-readable format using characters, numbers, and symbols. These files
usually have extensions like .txt, .csv, .html, etc. The content of a text file is made up of lines of text, and
when interacting with the file, Python reads and writes the file as a series of strings.
2. Binary Files
Binary files store data in a binary (0s and 1s) format, which is not human-readable. These files are often
used for storing multimedia files like images, videos, audio files, or any file that is not plain text. Binary
files are processed byte by byte, and Python reads and writes binary files in bytes.
To read a file in Python, you can use the open() function with the r mode (for reading).
file_path = "example.txt"
print(content)
print(content)
3. File Paths
In Python, paths to files and directories can be specified using either absolute paths or relative paths.
Absolute Path
An absolute path is the complete path to a file or directory from the root of the file system. It provides the
full hierarchy of directories needed to locate a file.
file_path = r"C:\Users\YourUsername\Documents\example.txt"
content = file.read()
print(content)
file_path = "/home/yourusername/Documents/example.txt"
content = file.read()
print(content)
Relative Path
A relative path refers to a location relative to the current working directory. The current working directory
is the folder where the Python script is being run. Relative paths are useful when you don't want to hard-
code absolute paths, making the code more portable.
content = file.read()
print(content)
To read the file line by line, you can use the .readline() method or iterate through the file object itself.
line = file.readline()
while line:
print(line.strip())
line = file.readline()
Once you’ve read the content (whether as a string or as a list of lines), you can manipulate it as needed.
content = file.read()
words = content.split()
7. Writing to a File
To write to a file, use the w mode (write). This will overwrite the file if it already exists.
If the file is empty, writing will simply insert content. If the file exists with content, opening in w mode
will empty the file before writing.
To write multiple lines, use the writelines() method or loop through a list of lines.
file.writelines(lines_to_write)
10. Appending to a File
Use the a mode (append) to add content to a file without erasing the existing content.
In Python, exceptions like ZeroDivisionError and FileNotFoundError occur when the program encounters
conditions that prevent it from executing further, such as dividing by zero or trying to access a file that
doesn't exist. If these exceptions aren't handled, the program will crash and stop running. To prevent this,
try-except blocks are used to handle these errors gracefully, allowing the program to continue running or
provide meaningful error messages.
Reasons for Handling Exceptions Like ZeroDivisionError and FileNotFoundError Using try-except
Blocks:
1. Avoiding Program Crashes: Without exception handling, encountering an error will terminate
the program. By using try-except blocks, you can catch the error and manage it without stopping
the program.
o Example for ZeroDivisionError:
o try:
o result = 10 / 0
o except ZeroDivisionError:
o print("Error: Cannot divide by zero.")
Without the try-except, dividing by zero would crash the program. Here, we catch the error
and handle it by printing a message.
2. Ensuring Correct File Handling (FileNotFoundError): When trying to access a file, there might
be a chance that the file doesn't exist or is inaccessible. Instead of crashing, handling FileNotFoundError
allows the program to take corrective actions, such as asking the user for a different file path or creating
the missing file.
Example for FileNotFoundError:
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("Error: The file was not found.")
Here, if the file is not found, the program won't crash but will inform the user about the issue.
Working with multiple files in Python is common in various tasks such as reading, writing, and
processing data across multiple files. You can manage multiple files by using loops, functions, or using
Python libraries like os, glob, or pathlib.
You can use a loop to iterate through a list of file paths and perform actions such as reading or writing.
try:
content = file.read()
print(f"Content of {file_path}:")
print(content)
except FileNotFoundError:
In this example, the loop iterates over the list file_paths, opening each file and printing its content. The
try-except block handles the case where a file is not found.
The os library helps in navigating directories and working with files, while glob can be used to search for
files with a specific pattern.
Example: Reading All .txt Files in a Directory
import os
import glob
txt_files = glob.glob('*.txt')
try:
content = file.read()
print(f"Content of {file_path}:")
print(content)
except FileNotFoundError:
In this example, glob.glob('*.txt') finds all .txt files in the current directory. You can modify the search
pattern to match files in subdirectories or files with other extensions.