0% found this document useful (0 votes)
4 views

unit-4 python

This document provides an overview of file handling in Python, detailing operations for reading and writing files, including advantages and disadvantages. It explains various file modes, methods for reading and writing, and the importance of closing files. Additionally, it covers file pointer manipulation, operations with files, and practical examples for programming, data processing, and system administration tasks.
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)
4 views

unit-4 python

This document provides an overview of file handling in Python, detailing operations for reading and writing files, including advantages and disadvantages. It explains various file modes, methods for reading and writing, and the importance of closing files. Additionally, it covers file pointer manipulation, operations with files, and practical examples for programming, data processing, and system administration tasks.
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/ 18

Unit-4

File handling in Python


Lecture 21. File Operations: Reading and Writing Files.
4.1 File handling in Python- Python supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files.
The concept of file handling has stretched over various other languages, but the implementation is either
complicated or lengthy, like other concepts of Python, this concept here is also easy and short. Python treats
files differently as text or binary and this is important. Each line of code includes a sequence of characters,
and they form a text file. Each line of a file is terminated with a special character, called the EOL or End of
Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new
one has begun.
4.1.1 Advantages of File Handling in Python
● Versatility: File handling in Python allows you to perform a wide range of operations, such as
creating, reading, writing, appending, renaming, and deleting files.
● Flexibility: File handling in Python is highly flexible, as it allows you to work with different file
types (e.g. text files, binary files, CSV files, etc.), and to perform different operations on files (e.g. read,
write, append, etc.).
● User–friendly: Python provides a user-friendly interface for file handling, making it easy to create,
read, and manipulate files.
● Cross-platform: Python file-handling functions work across different platforms (e.g. Windows,
Mac, Linux), allowing for seamless integration and compatibility.

4.1.2 Disadvantages of File Handling in Python


● Error-prone: File handling operations in Python can be prone to errors, especially if the code is not
carefullywritten or if there are issues with the file system (e.g. file permissions, file locks, etc.).
● Security risks: File handling in Python can also pose security risks, especially if the program accepts
user input that can be used to access or modify sensitive files on the system.
● Complexity: File handling in Python can be complex, especially when working with more advanced
file formats or operations. Careful attention must be paid to the code to ensure that files are handled
properly and securely.
● Performance: File handling operations in Python can be slower than other programming languages,
especiallywhen dealing with large files or performing complex operations.

Python provides built-in functions and methods to perform various file operations like reading, writing, and
updating files
4.2 Python File Open
Before performing any operation on the file like reading or writing, first, we have to open that file. For this, we
should use Python’s inbuilt function open() but at the time of opening, we have to specify the mode, which
represents the purpose of the opening file.
f = open(filename, mode)
Eg:- file = open('example.txt', 'r') # Opens the file in read mode
The mode argument is a string that specifies the mode in which the file is opened:
'r' for reading (default)

82
'w' for writing (creates a new file or truncates the file first)
'x' for exclusive creation (fails if the file already
exists) 'a' for appending (creates a new file if it
does not exist)'b' for binary mode
't' for text mode (default)
'+' for updating (reading and writing)
r+: To read and write data into the file. The previous data in the file will be
overridden. w+: To write and read data. It will override existing data.
a+: To append and read data from the file. It won’t override existing data.

83
Lecture 22. Discussed about How use read functions like read(), readline(), readlines().
4.3 Reading from a File
Once the file is opened, you can read its content using methods like read(), readline(), or
readlines():

# Read the entire file


content = file.read()
print(content)

# Read one line at a time


line = file.readline()
print(line)

# Read all lines into a list


lines = file.readlines()
print(lines)
file.close() # Always close the file when you're done with it

Q:-Python code to illustrate read() mode


file = open("cse.txt", "r")
print (file.read())

Output:
Hello world
Welcome CSE
123 456
Q:- In this example, we will see how we can read a file using the with statement in Python.
# Python code to illustrate with

with open("geeks.txt") as file:


data = file.read()
print(data)

84
Q:- Another way to read a file is to call a certain number of characters like in the following code the
interpreter will read the first five characters of stored data and return it as a string:
# Python code to illustrate read() mode character
wise file = open("geeks.txt", "r")
print (file.read(5))

Q:-We can also split lines while reading files in Python. The split() function splits the variable when space
is encountered. You can also split using any characters as you wish.
# Python code to illustrate split() function

with open("geeks.txt", "r") as file:


data = file.readlines()
for line in data:
word = line.split()
print (word)
OUTPUT:-
['Hello', 'world']
['CSE', ‘Welcome’]
['123', '456']
it-4

85
Lecture 23. Writing files in Python
4.4 Writing to a File
To write to a file, you need to open it in a write ('w'), append ('a'), or update ('+') mode. Then, use the
write() or writelines() methods:
Syntax:-
file = open('example.txt', 'w') # Open the file in write mode
file.write('Hello, World!\n') # Write a string to the file
lines = ['First line.\n', 'Second line.\n']
file.writelines(lines) # Write a list of strings to the file
file.close()
Closing a File
It's important to close the file when you're done with it to free up system resources. Use the close()
method: file.close()

Using with Statement


The with statement simplifies file handling by automatically taking care of closing the file once it leaves
the with block, even if exceptions occur:
Eg:-
with open('example.txt', 'r') as file:

content = file.read()
print(content)
# File is automatically closed here
Working of Append Mode
# Python code to illustrate append()
mode file = open('geek.txt', 'a')
file.write("This will add this line")
file.close()

4.5 Implementing all the functions in File Handling


import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)

def read_file(filename):
86
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)

def append_file(filename, text):


try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + "
successfully.") except IOError:
print("Error: could not append to file " + filename)

def rename_file(filename, new_filename):


try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + "
successfully.") except IOError:
print("Error: could not rename file " + filename)

def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted
successfully.") except IOError:
print("Error: could not delete file " + filename)

if name == ' main ':


filename = "example.txt"
new_filename = "new_example.txt"

create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)

Output:

File example.txt created successfully.


Hello, world!
87
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.

Handling File Paths


For file paths, you can use raw strings (e.g., r'C:\path\to\file.txt') to avoid escaping backslashes in Windows paths, or
use forward slashes which Python understands across platforms (e.g., 'C:/path/to/file.txt' or './folder/file.txt').

88
Lecture 24. Manipulating File Pointer
4.6 File Pointer Manipulation- In Python, you can manipulate the file pointer, which represents the current position in
the file where the next read or write operation will occur. Python provides the seek() method to move the file pointer to
a specific position within thefile.
Syntax:-
f.seek(offset, from_what), where f is file pointer

The seek() method takes two arguments:

1. offset: The number of bytes to move the file pointer. Positive values move the pointer forward, negative values
move it backward.
2. from_what: This argument specifies the reference point for the offset. It can take one of three values:
● 0 (default): The beginning of the file.
● 1: The current file position.
● 2: The end of the file.

By default from_what argument is set to 0.


Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to 0.

Example:-
Example 1: Let’s suppose we have to read a file named “CSE.txt” which contains the following
text: "Code is like humor. When you have to explain it, it’s bad."

f = open("CSE.txt", "r")

# Second parameter is by default 0


# sets Reference point to twentieth index position from the beginning
f.seek(20)

# prints current position


print(f.tell())

print(f.readline())
f.close()

Output:
20
When you have to explain it, it’s bad.
Example 2: Seek() function with negative offset only works when file is opened in binary mode. Let’s suppose
the binary file contains the following text.

b'Code is like humor. When you have to explain it, its bad.'
f = open("data.txt", "rb")
89
# sets Reference point to tenth #
position to the left from end
f.seek(-10, 2)

# prints current position


print(f.tell())

# Converting binary to string and


# printing
print(f.readline().decode('utf-8'))

f.close()

Output:
47
, its bad.

Example3:- seek() method to manipulate the file pointer:


# Open a file in read mode
file = open('example.txt', 'r')

# Move the file pointer to the 10th byte from the beginning
file.seek(10)

# Read the content from the current position


content = file.read()
print(content)

# Move the file pointer 5 bytes backward from the current position
file.seek(-5, 1)

# Read the content from the current position


content = file.read()
print(content)

# Move the file pointer to the end of the file


file.seek(0, 2)

# Write content at the end of the file


file.write("\nAdding content at the end.")

# Close the
filefile.close()
In this example:

90
The first seek(10) call moves the file pointer to the 10th byte from the beginning of the file.
The second seek(-5, 1) call moves the file pointer 5 bytes backward from the current position.
The third seek(0, 2) call moves the file pointer to the end of the file.
It's important to note that seeking beyond the end of the file when writing will cause the file to be extended
with null bytes up to the specified position. Therefore, you can seek beyond the end of the file when writing to
append data. However, seeking beyond the end of the file when reading will result in an error.

Lecture 25. File of Operations

4.7 File of Operations-Using a file of operations typically involves reading from or writing to a file that contains a
series of instructions or data manipulations. These operations can vary widely depending on the context, such as
programming, data processing, or system administration. Let's break down how to approach this in a few different
scenarios:

4.7.1 Programming and Scripting


In programming, a file of operations might contain a list of commands or function calls that should be executed
sequentially. Here’s how you might approach this:

Reading the File:


Open the file in the appropriate mode (read, write, append, etc.).
Read the file line by line or as a whole, depending on your needs.

Parsing the Operations:


For each line or operation, parse the instruction. This could involve simple string manipulation or more complex
parsing if the instructions are in a specific format (JSON, XML, etc.).
It’s essential to implement error handling to deal with malformed instructions or unsupported operations.

Executing the Operations:


Execute each parsed operation. This might involve calling functions, executing system commands, or performing file
manipulations.
Ensure that operations are executed in the correct order and handle any dependencies between operations.

4.7.2 Data Processing


In data processing, a file of operations might list data transformations or analyses to perform on a dataset. This could
involve:

Reading and Writing Data:


Use appropriate libraries for data manipulation (e.g., pandas in Python) to read your dataset.
Read the operations file to determine what transformations or analyses need to be performed.

Performing Operations:
For each operation, apply the corresponding data transformation. This might involve filtering data, performing
calculations, or aggregating information.
After performing an operation, you might need to write the result to a file or prepare it for the next operation.

91
4.7.3 System Administration
For system administration, a file of operations might contain a list of system commands or configuration changes to
apply to a server or network of computers.

Automating Tasks:
Use a scripting language suitable for system administration (such as Bash for Linux/Unix systems or PowerShell for
Windows).
Read each operation from the file and use the script to execute the corresponding system command or change the
system configuration.

Ensuring System Integrity:


Implement checks to verify that each operation completes successfully.
Log the outcomes of operations for audit purposes and to troubleshoot any issues that arise.

General Tips
Error Handling: Always include error handling to manage unexpected or malformed operations gracefully.
Logging: Keep a log of operations performed and any errors or warnings generated. This is invaluable for debugging
and verifying that operations have been executed correctly.
Security: Be cautious when executing operations from a file, especially if the operations involve system commands or
could impact data integrity. Validate and sanitize the operations to prevent security vulnerabilities.
By breaking down the process into manageable steps and considering the context in which you're using the file of
operations, you can effectively implement and automate a wide range of tasks.

Above Operation in case of Python Language

1. Programming and Scripting


Suppose you have a file named operations.txt with lines of operations like:

print,Hello World!
add,3,5

You want to read these operations and execute them. Let's assume add operation sums the numbers. def

handle_print(args):
print(*args)

def handle_add(args):
result = sum(map(int, args))
print(result)

# Mapping operation names to functions


operations = {
'print': handle_print,
'add': handle_add,
}
92
with open('operations.txt', 'r') as file:
for line in file:
op, *args = line.strip().split(',')
if op in operations:
operations[op](args)
else:
print(f"Unsupported operation: {op}")

2. Data Processing
Imagine you have a CSV file data.csv and an operations file data_operations.txt that contains operations like filter, >10
and average. For simplicity, let's handle a single operation: filtering values greater than 10.

Program:-
import pandas as pd
# Assuming a simple CSV file with one column of integers
df = pd.read_csv('data.csv')

with open('data_operations.txt', 'r') as file:


for line in file:
operation, value = line.strip().split(',')
if operation == 'filter':
df = df[df['column_name'] > int(value)]

# Assuming you might want to print or save the filtered data


print(df)

3. System Administration
For system administration, let's automate the creation of backup files. Assume an operations file system_ops.txt with
content like backup,/path/to/file.

import shutil
import os

def backup_file(file_path):
if os.path.exists(file_path):
shutil.copy(file_path,
f"{file_path}.backup") print(f"Backup
created for {file_path}")
else:
print(f"File does not exist: {file_path}")

with open('system_ops.txt', 'r') as file:


for line in file:
operation, path = line.strip().split(',')
if operation == 'backup':

93
backup_file(path)

General Python Tips for Handling Files of Operations


Use Context Managers: Always use with open(...) as ... for safely opening and closing files.
Error Handling: Wrap operations in try/except blocks to gracefully handle exceptions.
Dynamic Function Mapping: As shown in the programming example, map operation names to functions for a
clean and scalable way to execute operations.
Validate Inputs: Especially when executing system operations or modifying data, validate and sanitize inputs to
prevent errors or security issues.
(Examples) :- Python Program (Fibonacci Series)

Program:- Discussed about Fibonacci Series of Program.


The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually
starting with 0 and 1. That is, the sequence starts 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. It's a classic example used in
programming to demonstrate various coding techniques, including recursion, iteration, and dynamic programming.

1. Recursive Approach
The recursive approach directly implements the mathematical definition of the Fibonacci sequence. However, it's not
efficient for large numbers due to repeated calculations and a high recursive call stack usage.

def fibonacci_recursive(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

# Example usage:
n = 10
print(f"The {n}th Fibonacci number (recursive) is: {fibonacci_recursive(n)}")

2. Iterative Approach
The iterative approach uses a loop to calculate the Fibonacci numbers up to n. This method is much more efficient than
recursion for large numbers.

def fibonacci_iterative(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a

# Example usage:
n = 10
print(f"The {n}th Fibonacci number (iterative) is: {fibonacci_iterative(n)}")

94
Python Program(Matrix Addition)

Program: - Discussed about Addition of two Matrix of Program.


Adding two matrices in Python can be done in various ways, ranging from basic loops to using sophisticated libraries
like NumPy, which is designed for scientific computing and can handle operations on large multi-dimensional arrays
and matrices efficiently.

def add_matrices(matrix1, matrix2):


# Ensure the matrices have the same dimensions
if len(matrix1) != len(matrix2) or len(matrix1[0]) !=
len(matrix2[0]): return "Matrices are of different sizes."

# Create a new matrix to store the result


result_matrix = [[0 for _ in range(len(matrix1[0]))] for _ in range(len(matrix1))]

# Iterate over the matrices to add corresponding elements


for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]

return result_matrix
# Example usage
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

print("Resultant Matrix:")
for row in add_matrices(matrix1, matrix2):
print(row)

Python Program(Transpose Matrix of Program.)

Program:-
Transposing a matrix means flipping a matrix over its diagonal, turning the matrix's rows into columns and columns
into rows. This operation is common in mathematics and programming, especially in the context of linear algebra and
data manipulation.
95
Basic Python Loops: Good for educational purposes and environments where external dependencies are discouraged
or not allowed. However, manually coding the transpose operation can be error-prone for complex data structures.
Using NumPy: Offers a simple, efficient, and less error-prone method for transposing matrices. Highly recommended
for scientific computing, data analysis, and any application requiring manipulation of large numerical datasets.

Program(Using Python Loops)

def transpose_matrix(matrix):
# Initialize the transposed matrix with zeros
transposed = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]

# Iterate through rows


for i in range(len(matrix)):
# Iterate through columns
for j in
range(len(matrix[i])):
# Assign transposed values
transposed[j][i] =
matrix[i][j]

return transposed

# Example usage
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed_matrix = transpose_matrix(matrix)

print("Original
Matrix:") for row in
matrix:
print(row)

print("\nTransposed Matrix:")
for row in transposed_matrix:
print(row)

Python Program (Identity Matrix)

Program:- Python identity Matrix of Program.

def identity_matrix(n):
"""Create an n x n identity matrix."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]

# Example usage
n=4
96
print("Identity Matrix of size",
n) for row in identity_matrix(n):
print(row)

Python Program (Multiplication table)

Python Program:- Python program to Print any no of table Program.

def print_multiplication_table(number, range_limit):


"""
Prints the multiplication table for a given number up to a specified range.

Parameters:
number (int): The number for which the multiplication table is to be printed.
range_limit (int): The range up to which the table should be printed.
"""
for i in range(1, range_limit + 1):
print(f"{number} x {i} = {number *
i}")

def main():
# Prompt the user for input
number = int(input("Enter the number for the multiplication table: "))
range_limit = int(input("Enter the range up to which to print the table: "))

# Print the multiplication table


print(f"\nMultiplication table for {number} up to
{range_limit}:") print_multiplication_table(number, range_limit)

if name == " main ":


main()

Python Program (Leap Year)

Program:- Python Program how to check given year is leap or not

def is_leap_year(year):
"""
Returns True if the given year is a leap year, False otherwise.
"""
# Year is divisible by 4
if year % 4 == 0:
# Year is not divisible by 100 unless it's also divisible by 400
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False

97
else:
return True
else:
return False

def main():
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap
year.") else:
print(f"{year} is not a leap year.")

if name == " main ":


main()
Python Program (Perfect Number)

Program:- Python Perfect number

program

A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. For example, 28 is
a perfect number because its divisors are 1, 2, 4, 7, and 14, and
1+2+4+7+14=28

Below is a Python program that checks if a given number is a perfect number. The program defines a function to
calculate the sum of divisors of a number and then checks if this sum equals the number itself.

def is_perfect_number(number):
if number < 1:
return False

sum_of_divisors = 0
# Check for divisors of the number
for possible_divisor in range(1, number):
if number % possible_divisor == 0:
sum_of_divisors += possible_divisor

# Compare the sum of divisors (excluding the number itself) to the number
return sum_of_divisors == number

def main():
number = int(input("Enter a number: "))
if is_perfect_number(number):
print(f"{number} is a perfect number.")
else:
print(f"{number} is not a perfect number.")

if name == " main ":

98
main()

Python Program (Armstrong Number)

Program:- Python Armstrong number

program

An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each
raised to the power of the number of digits. For example, 153 is an Armstrong number because it has 3 digits, and
13 +53+33 =153

To write a Python program that checks if a given number is an Armstrong number, you need to:

● Get the number of digits in the number.


● Calculate the sum of the digits each raised to the power of the number of digits.
● Compare the sum to the original number.

Here's a Python program that performs these steps:

def is_armstrong_number(number):
# Convert the number to a string to easily iterate over its digits
str_number = str(number)
# Calculate the number of digits
num_digits = len(str_number)

# Calculate the sum of digits raised to the power of the number of digits
sum_of_powers = sum(int(digit) ** num_digits for digit in str_number)

# Compare the sum to the original number


return sum_of_powers == number

def main():
number = int(input("Enter a number: "))
if is_armstrong_number(number):
print(f"{number} is an Armstrong
number.") else:
print(f"{number} is not an Armstrong number.")

if name == " main ":


main()
Important Ques -CO4
i. Discuss various file opening mode in python (2020-21)
ii. Discuss Exceptions and Assertions in Python. Explain with a suitable example. Explain any two built-in
exceptions.(2021-22, 2019-20)
iii. There is a file named Input .Txt. Enter some positive numbers into the file named Input.Txt .Read the contents of
the file and if it is an odd number write it to ODD.Txt and if the number is even , write it to EVEN,Txt. (2021-22)
iv. What are file input and output operations in python programming? (2019-20, 2020-21)
v. Write a python program to read the content of a file and then create a file COUNT.Txt to write the
numbers of lettersand digits of the readed content from the given file (2022-23)
99

You might also like