unit-4 python
unit-4 python
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():
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
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
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()
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()
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 delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted
successfully.") except IOError:
print("Error: could not delete file " + filename)
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:
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
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.
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")
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)
f.close()
Output:
47
, its bad.
# Move the file pointer to the 10th byte from the beginning
file.seek(10)
# Move the file pointer 5 bytes backward from the current position
file.seek(-5, 1)
# 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.
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:
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.
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.
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)
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')
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}")
93
backup_file(path)
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)
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)
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.
def transpose_matrix(matrix):
# Initialize the transposed matrix with zeros
transposed = [[0 for _ in range(len(matrix))] for _ in range(len(matrix[0]))]
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)
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)
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: "))
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.")
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.")
98
main()
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:
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)
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.")