0% found this document useful (0 votes)
16 views5 pages

Python File Operations and Classes

The document contains two Python programs. The first program (6a) accepts a file name from the user, displays the first N lines of the file, and finds the frequency of a word entered by the user. The second program (6b) creates a ZIP file from a user-specified folder containing multiple files. The document also contains two additional Python programs. The first (7a) uses inheritance to calculate the area of shapes like circles, rectangles, and triangles. The second (7b) creates an Employee class to store employee details like name, ID, department, and salary, and includes a method to update salaries for employees in a given department.

Uploaded by

Rahul Kumar
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)
16 views5 pages

Python File Operations and Classes

The document contains two Python programs. The first program (6a) accepts a file name from the user, displays the first N lines of the file, and finds the frequency of a word entered by the user. The second program (6b) creates a ZIP file from a user-specified folder containing multiple files. The document also contains two additional Python programs. The first (7a) uses inheritance to calculate the area of shapes like circles, rectangles, and triangles. The second (7b) creates an Employee class to store employee details like name, ID, department, and salary, and includes a method to update salaries for employees in a given department.

Uploaded by

Rahul Kumar
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

6.

a) a) Write a python program to accept a file name from the user


and perform the following operations
1. Display the first N line of the file
2. Find the frequency of occurrence of the word accepted from the
user in the file
import [Link]

import sys

fname = input("Enter the filename : ")

if not [Link](fname):

print("File", fname, "doesn't exists")

[Link](0)

infile = open(fname, "r")

lineList = [Link]()

#print(lineList)

for i in range(len(lineList)):

print(lineList[i])

word = input("Enter a word : ")

cnt = 0

for line in lineList:

cnt += [Link](word)

print("The word", word, "appears", cnt, "times in the file")

6.b) Write a python program to create a ZIP file of a particular folder


which contains several files inside it.

import os

import sys
import pathlib

import zipfile

dirName = input("Enter Directory name that you want to backup : ")

if not [Link](dirName):

print("Directory", dirName, "doesn't exists")

[Link](0)

curDirectory = [Link](dirName)

with [Link]("[Link]", mode="w") as archive:

for file_path in [Link]("*"):

[Link](file_path,
arcname=file_path.relative_to(curDirectory))

if [Link]("[Link]"):

print("Archive", "[Link]", "created successfully")

else:

print("Error in creating zip archive")

7.a) By using the concept of inheritance write a python program to


find the area of triangle, circle and rectangle.
import math

class Shape:

def __init__(self):

[Link] = 0

[Link] = ""

def showArea(self):

print("The area of the", [Link], "is", [Link], "units")


class Circle(Shape):

def __init__(self,radius):

[Link] = 0

[Link] = "Circle"

[Link] = radius

def calcArea(self):

[Link] = [Link] * [Link] * [Link]

class Rectangle(Shape):

def __init__(self,length,breadth):

[Link] = 0

[Link] = "Rectangle"

[Link] = length

[Link] = breadth

def calcArea(self):

[Link] = [Link] * [Link]

class Triangle(Shape):

def __init__(self,base,height):

[Link] = 0

[Link] = "Triangle"

[Link] = base

[Link] = height

def calcArea(self):

[Link] = [Link] * [Link] / 2


c1 = Circle(5)

[Link]()

[Link]()

r1 = Rectangle(5, 4)

[Link]()

[Link]()

t1 = Triangle(3, 4)

[Link]()

[Link]()

7b. Write a python program by creating a class called Employee to


store the details of Name, Employee ID, Department and Salary, and
implement a method to update salary of employees belonging to a given
department.

class Employee:

def _init_(self):

[Link] = ""

[Link] = ""

[Link] = ""

[Link] = 0

def getEmpDetails(self):

[Link] = input("Enter Employee name : ")

[Link] = input("Enter Employee ID : ")

[Link] = input("Enter Employee Dept : ")

[Link] = int(input("Enter Employee Salary : "))


def showEmpDetails(self):

print("Employee Details")

print("Name : ", [Link])

print("ID : ", [Link])

print("Dept : ", [Link])

print("Salary : ", [Link])

def updtSalary(self):

[Link] = int(input("Enter new Salary : "))

self.a=[Link]+[Link]

print("Updated Salary", self.a)

e1 = Employee()

[Link]()

[Link]()

[Link]()

Common questions

Powered by AI

Accepting filenames and directory names from user input can lead to security vulnerabilities such as path traversal attacks, where a user might input a path that navigates outside restricted directories. There is also the risk of file corruption or deletion if paths aren't properly validated. Implementing strict validation of input paths, avoiding symbolic links, and using controlled environments or role-based access controls are critical in mitigating these security risks .

Using readlines() reads the entire file into memory, which can be inefficient and memory-intensive for large files. This approach might lead to memory errors if the file size exceeds the available memory. A more efficient method could be to iterate over the file object, line by line, which handles large files without excessive memory usage .

The program captures user input to specify a directory and uses zipfile.ZipFile to create a ZIP archive. While it checks for directory existence before proceeding, it does not handle exceptions that may arise during the file creation process, such as permission errors or disk space issues. Improvements could include using try-except blocks around archive operations to handle such exceptions gracefully, providing the user with more informative error messages .

The current implementation updates the salary through direct input and calculation in a method of an Employee object. For scalability and handling multiple employees, it would be beneficial to store employees in a collection, like a list or dictionary, which allows iteration and updating salaries conditionally based on criteria such as department. Additionally, the update process could be decoupled into a separate method that accepts parameters rather than relying solely on inputs during the call .

The program calculates geometric areas using standard formulas and assigns the result to the area attribute of each shape class. However, floating-point arithmetic can introduce precision errors, particularly with small or very large numbers. Implementing error checking or using Python's decimal module could help enhance precision. Additionally, abstracting computation into separate methods and allowing for parameterization could improve flexibility and reuse .

Inheritance allows the program to define a base class, Shape, which includes common attributes or methods (such as the area attribute and showArea() method) that are shared by all derived classes (Circle, Rectangle, and Triangle). This avoids code duplication and provides a unified interface for different shapes, promoting modularity and code reuse. Each shape-specific class computes its area using its own logic, which is made possible by extending the base class .

The program ensures that the ZIP archive contains files with relative paths by using arcname inside the archive.write() method, which maps to each file's relative path from the directory to be archived. This is important because it avoids embedding absolute paths in archives, which can cause extraction issues on other systems where those paths do not exist, maintaining portability and flexibility .

The program first checks if the specified file or directory exists using os.path.isfile() for files or os.path.isdir() for directories. If the specified file or directory does not exist, it prints a message stating that it doesn't exist and exits the program using sys.exit(0).

Encapsulation is used in the Employee class by encapsulating employee details (name, ID, department, and salary) as attributes within the class, and providing methods like getEmpDetails(), showEmpDetails(), and updtSalary() to interact with these attributes. This prevents direct manipulation from outside the class, enforcing controlled access through defined interfaces .

The programs employ basic error handling such as checking file or directory existence before proceeding. However, they do not encompass more robust error handling for invalid input types or values, such as non-integer inputs for salary or radius. Implementing try-except blocks to catch exceptions for invalid input types and providing clear prompts or retries can significantly improve the user experience and program robustness .

You might also like