[go: up one dir, main page]

0% found this document useful (0 votes)
19 views7 pages

Unit Iv-1

Uploaded by

anas123jamia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views7 pages

Unit Iv-1

Uploaded by

anas123jamia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIT IV

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.

Types of Files in Python

Files in Python are broadly classified into two types:

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.

 Examples: .txt, .csv, .html, .xml

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.

 Examples: .jpg, .png, .exe, .bin, .mp3, .mp4

1. Reading from a File

To read a file in Python, you can use the open() function with the r mode (for reading).

# Opening a file and reading its content

file_path = "example.txt"

with open(file_path, "r") as file:

content = file.read() # Reads the entire file content

print(content)

2. Reading an Entire File


Use the .read() method to read the entire file content as a string.

with open(file_path, "r") as file:

content = file.read() # Reads the entire file 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.

 On Windows, an absolute path typically starts with a drive letter (C:\).


 On Unix-like systems (Linux, macOS), it starts from the root directory (/).

# Absolute path on Windows

file_path = r"C:\Users\YourUsername\Documents\example.txt"

with open(file_path, 'r') as file:

content = file.read()

print(content)

# Absolute path on Linux/Mac

file_path = "/home/yourusername/Documents/example.txt"

with open(file_path, 'r') as file:

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.

 . (dot) represents the current directory.


 .. (double dot) represents the parent directory.
Example of Relative Path

Assume the current working directory is /home/yourusername/Documents/.

# Relative path (current directory)

file_path = "example.txt" # Points to /home/yourusername/Documents/example.txt

with open(file_path, 'r') as file:

content = file.read()

print(content)

4. Reading Line by Line

To read the file line by line, you can use the .readline() method or iterate through the file object itself.

# Method 1: Using a loop

with open(file_path, "r") as file:

for line in file:

print(line.strip()) # Prints each line, stripping the newline character

# Method 2: Using readline()

with open(file_path, "r") as file:

line = file.readline()

while line:

print(line.strip())

line = file.readline()

5. Making a List of Lines from a File

You can use .readlines() to get a list of all lines in a file.

with open(file_path, "r") as file:

lines = file.readlines() # Returns a list of lines


print(lines)

6. Working with the File’s Content

Once you’ve read the content (whether as a string or as a list of lines), you can manipulate it as needed.

# Example: Count the number of words in the file

with open(file_path, "r") as file:

content = file.read()

words = content.split()

print(f"Word count: {len(words)}")

7. Writing to a File

To write to a file, use the w mode (write). This will overwrite the file if it already exists.

# Writing a single line to a file

with open("output.txt", "w") as file:

file.write("This is a new file!\n")

8. Writing to an Empty File

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.

# Writing to an empty file (or overwriting existing content)

with open("empty_file.txt", "w") as file:

file.write("This is the first line of the empty file.\n")

9. Writing Multiple Lines

To write multiple lines, use the writelines() method or loop through a list of lines.

# Writing multiple lines to a file

lines_to_write = ["First line\n", "Second line\n", "Third line\n"]

with open("multiple_lines.txt", "w") as file:

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.

# Appending content to a file

with open("output.txt", "a") as file:

file.write("This is appended text.\n")

Key Modes for Opening Files:

 r: Read (default mode)


 w: Write (overwrites the file)
 a: Append (adds content to the end of the file)
 r+: Read and write (starts from the beginning)
 w+: Write and read (overwrites the file)
 a+: Append and read (can read and append content)

Exception Handling in Python

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

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.

1. Using Loops to Process Multiple Files

You can use a loop to iterate through a list of file paths and perform actions such as reading or writing.

Example: Reading Multiple Files

file_paths = ['file1.txt', 'file2.txt', 'file3.txt']

for file_path in file_paths:

try:

with open(file_path, 'r') as file:

content = file.read()

print(f"Content of {file_path}:")

print(content)

except FileNotFoundError:

print(f"Error: {file_path} not found.")

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.

2. Using the os and glob Libraries

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

# List all text files in the current directory

txt_files = glob.glob('*.txt')

for file_path in txt_files:

try:

with open(file_path, 'r') as file:

content = file.read()

print(f"Content of {file_path}:")

print(content)

except FileNotFoundError:

print(f"Error: {file_path} not found.")

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.

You might also like