0% found this document useful (0 votes)
2 views17 pages

Python File Handling Module5 Answers

The document provides detailed explanations and examples of various Python file handling techniques, including path components, the shelve module, file properties, and the shutil module. It covers file reading/writing processes, ZIP file operations, and directory management using os and pathlib modules. Additionally, it includes sample Python programs demonstrating these concepts in practice.

Uploaded by

harshitprasad09
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)
2 views17 pages

Python File Handling Module5 Answers

The document provides detailed explanations and examples of various Python file handling techniques, including path components, the shelve module, file properties, and the shutil module. It covers file reading/writing processes, ZIP file operations, and directory management using os and pathlib modules. Additionally, it includes sample Python programs demonstrating these concepts in practice.

Uploaded by

harshitprasad09
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

Python File Handling and Modules - Exam Answers

1. Explain the components of a path with an example. Differentiate between


absolute and relative paths with an example.
Components of a Path:
A file path shows the location of a file or folder in a computer.

Example:
C:/Users/Ruma/Documents/[Link]

Components:
1. Drive → C:
2. Folder → Users
3. Subfolder → Documents
4. File name → file
5. Extension → .txt

Absolute Path:
An absolute path gives the complete location of a file from the root directory.

Example:
C:/Users/Ruma/Documents/[Link]

Relative Path:
A relative path gives the location of a file with respect to the current folder.

Example:
Documents/[Link]

Difference:
Absolute path starts from the root directory, whereas relative path starts from the current
directory.

2. Explain the shelve module with a suitable example.


The shelve module is used to store Python objects in a file like a dictionary.

Features:
• Stores data permanently
• Data can be retrieved later
• Uses key-value pairs
Example:
import shelve

data = [Link]('student')
data['name'] = 'Ruma'
data['marks'] = 90
[Link]()

# Retrieving data
data = [Link]('student')
print(data['name'])
[Link]()

Output:
Ruma

3. What are the two properties of a file? Explain how slash (/) operator is used
to join path.
Two properties of a file:
1. File Name – Name of the file.
2. File Extension – Type of file such as .txt, .py, .jpg etc.

Using slash (/) to join paths:


Python's pathlib module uses / operator to join paths easily.

Example:
from pathlib import Path

path = Path('Folder') / '[Link]'


print(path)

Output:
Folder/[Link]

4. Write a Python program to read ZIP files.


Program:
import zipfile

zip_file = [Link]('[Link]', 'r')


print(zip_file.namelist())

zip_file.close()

Explanation:
• zipfile module is used to work with ZIP files.
• namelist() displays all files inside the ZIP file.

5. Explain the following with Example:


1. Current working directory
2. Creating a new directory
1. Current Working Directory:
The current working directory is the folder where the Python program is running.

Example:
import os

print([Link]())

Output:
Displays the current folder path.

2. Creating a New Directory:


mkdir() is used to create a new folder.

Example:
import os

[Link]('NewFolder')

Output:
Creates a folder named NewFolder.

6. Explain how to get the Parts of a File Path and Finding File Sizes and Folder
Contents.
Getting Parts of a File Path:
Example:
from pathlib import Path

path = Path('C:/Users/Ruma/[Link]')
print([Link])
print([Link])
print([Link])

Output:
[Link]
file
.txt

Finding File Size:


Example:
import os

size = [Link]('[Link]')
print(size)

Finding Folder Contents:


Example:
import os

files = [Link]('.')
print(files)

Output:
Displays all files and folders in the current directory.

7. Explain the shutil module and the various functions the module provides
with an example for each.
The shutil module is used for high-level file operations.

1. copy() – Copies file


Example:
import shutil
[Link]('[Link]', '[Link]')

2. move() – Moves file


Example:
[Link]('[Link]', 'Folder')

3. copytree() – Copies entire folder


Example:
[Link]('Folder1', 'Folder2')
4. rmtree() – Deletes folder
Example:
[Link]('Folder2')

5. make_archive() – Creates ZIP file


Example:
shutil.make_archive('backup', 'zip', 'Folder1')

8. What is the purpose of the shelve module in Python? How is it different from
writing data to a plain text file? Write a short example demonstrating how to
save and retrieve data using shelve.
Purpose of shelve module:
The shelve module stores Python objects permanently in a file.

Difference from Plain Text File:


• Shelve stores objects directly.
• Text file stores only text data.
• Shelve works like a dictionary.

Example:
import shelve

data = [Link]('store')
data['city'] = 'Bangalore'
[Link]()

data = [Link]('store')
print(data['city'])
[Link]()

Output:
Bangalore

9. Describe the complete file reading/writing process in Python. Explain the


different modes used when opening a file and the role of the close() method.
What is the advantage of using with statement?
File Reading/Writing Process:
1. Open the file
2. Read or write data
3. Close the file
Example:
file = open('[Link]', 'w')
[Link]('Hello')
[Link]()

File Modes:
1. r → Read mode
2. w → Write mode
3. a → Append mode
4. x → Create file
5. rb → Read binary file
6. wb → Write binary file

Role of close():
close() saves changes and releases memory.

Advantage of with statement:


• Automatically closes the file
• Easier and safer

Example:
with open('[Link]', 'r') as file:
print([Link]())

10. A weather department records daily temperature readings in a file named


[Link]. Each line in the file contains one temperature value (in °C).
Sample file content:
30
32
28
35
31
Write a Python program to:
• Read the temperature file
• Calculate the average temperature
• Display the result
Program:
file = open('[Link]', 'r')
temps = [Link]()

total = 0

for t in temps:
total = total + int(t)

average = total / len(temps)

print('Average Temperature =', average)

[Link]()

Output:
Average Temperature = 31.2

11. A teacher collects student essays in a file named [Link] for


evaluation. Before grading, the teacher wants to check whether the essay
meets the minimum word limit requirement.
Write a Python program that:
• Reads the contents of [Link]
• Counts the total number of words in the essay
• Displays the total word count

Program:
# Open the essay file

file = open('[Link]', 'r')

# Read the contents of the file

text = [Link]()

# Split the text into words

words = [Link]()

# Count the number of words


count = len(words)

# Display total word count

print("Total Word Count =", count)

# Close the file

[Link]()
[Link]()

Sample Output:

Total Word Count = 125

Explanation:
• read() reads the complete file.
• split() separates words.
• len() counts the total number of words.

12. Explain saving variables with the [Link]() function with a suitable
example.
The pprint module is used to print data structures in a neat and readable format.

[Link]() converts Python objects into formatted string data.

Example:
import pprint

data = {'Name':'Ruma', 'Marks':[90, 85, 88]}

text = [Link](data)

file = open('[Link]', 'w')


[Link](text)
[Link]()

Explanation:
• pformat() converts dictionary into string.
• The string is saved into the file.

13. What is ZIP file? Write a Python program to:


• Read ZIP files
• Extract files from ZIP files
• Create a ZIP file and add the files to it
ZIP File:
A ZIP file is a compressed file used to store one or more files together.

Program:

import zipfile

# Reading ZIP file


zipobj = [Link]('[Link]')
print([Link]())

# Extracting files
[Link]('ExtractFolder')

# Creating ZIP file


newzip = [Link]('[Link]', 'w')
[Link]('[Link]')
[Link]()

Explanation:
• namelist() displays files inside ZIP.
• extractall() extracts files.
• write() adds files into ZIP.

14. A file manager application needs to handle file paths efficiently. Explain the
following with example
Create a file path using [Link]().
• Separate the directory and file name using [Link]()
• Check whether the file exists using [Link]().
• Display the file size using [Link]().

1. Create file path using [Link]()

Example:
import os
path = [Link]('Folder', '[Link]')
print(path)

2. Separate directory and file name using [Link]()

Example:
print([Link](path))

3. Check file exists using [Link]()

Example:
print([Link](path))

4. Display file size using [Link]()

Example:
print([Link](path))

Explanation:
• join() combines paths.
• split() separates folder and file.
• exists() checks file availability.
• getsize() displays file size.

15. What is File? Write a Python program that demonstrates:


• Opening and closing File
• Reading contents of File
• Writing data into File
File:
A file is a collection of data stored permanently in a storage device.

Program:

# Writing data
file = open('[Link]', 'w')
[Link]('Hello Python')
[Link]()

# Reading data
file = open('[Link]', 'r')
content = [Link]()
print(content)
[Link]()

Explanation:
• open() opens the file.
• write() stores data.
• read() reads data.
• close() closes the file.

16. What is shutil? Write a Python program using shutil library functions to:

• Copying Files and Folders

• Moving and Renaming Files and Folders

• Permanently Deleting Files and Folders.

shutil:
The shutil module is used for high-level file operations.

Program:

import shutil

import os

# Copying a file

[Link]('[Link]', 'copy_file1.txt')

print("File copied successfully")

# Copying a folder

[Link]('Folder1', 'Folder2')

print("Folder copied successfully")

# Moving and renaming a file


[Link]('copy_file1.txt', 'NewFolder/[Link]')

print("File moved and renamed successfully")

# Permanently deleting a folder

[Link]('Folder2')

print("Folder deleted successfully")

Sample Output:

File copied successfully

Folder copied successfully

File moved and renamed successfully

Folder deleted successfully

Explanation:

1. [Link]()

Copies a file from one location to another.

Example:

[Link]('[Link]', 'copy_file1.txt')

2. [Link]()

Copies an entire folder along with all files.

Example:

[Link]('Folder1', 'Folder2')

3. [Link]()

Moves or renames files and folders.

Example:

[Link]('copy_file1.txt', 'NewFolder/[Link]')
4. [Link]()

Deletes a folder permanently.

Example:

[Link]('Folder2')

17. A company stores employee salary details in a text file named


[Link].
Each record contains:
• Employee ID • Employee Name • Monthly Salary
The file format is:
E101, Arun Kumar, 45000
E102, Meena R, 52000
E103, Ravi S, 39000
E104, Priya K, 61000
Write a Python program to:
• Read the salary file
• Calculate the total monthly payroll
• Display the total payroll amount

Program:

# Open the salary file

file = open('[Link]', 'r')

total = 0

# Read each line from the file

for line in file:

# Split the line using comma


data = [Link](',')

# Get salary value

salary = int(data[2])

# Add salary to total

total = total + salary

# Display total payroll

print("Total Monthly Payroll =", total)

# Close the file

[Link]()

Explanation:

• open() → Opens the file.


• split(',') → Separates Employee ID, Name, and Salary.
• int() → Converts salary into integer value.
• Total salary is calculated using a loop.

Sample Output:

Total Monthly Payroll = 197000

18. Explain the following with an example:


[Link]()
[Link]()
[Link]()
[Link]()
1. [Link]()
Displays current working directory.

Example:
from pathlib import Path
print([Link]())

2. [Link]()
Changes current directory.

Example:
import os
[Link]('D:/Python')

3. [Link]()
Displays home directory.

Example:
from pathlib import Path
print([Link]())

4. [Link]()
Creates multiple directories.

Example:
import os
[Link]('Folder/SubFolder')

19. Explain [Link]() with a diagram, and write a Python program that prints
the names of folders, sub-folders, and files.
[Link]():
[Link]() is used to traverse all folders, subfolders, and files.

Diagram:

MainFolder
|
|-- SubFolder1
| |-- [Link]
|
|-- SubFolder2
|-- [Link]

Program:

import os
for folder, subfolders, files in [Link]('MainFolder'):
print('Folder:', folder)
print('Subfolders:', subfolders)
print('Files:', files)

Explanation:
• [Link]() visits every folder one by one.

20. A company stores project files in different folders. The user provides a
folder path and a file name separately. Write a Python program to:
• Join the folder path and file name correctly
• Check whether the file exists
• Display the absolute path and relative path of the file Use appropriate
functions from [Link].

Program:

import os

# Folder path and file name

folder = "Projects"

filename = "[Link]"

# Join folder path and file name

path = [Link](folder, filename)

print("Joined Path:", path)

# Check whether file exists

if [Link](path):

print("File exists")
else:

print("File does not exist")

# Display absolute path

print("Absolute Path:", [Link](path))

# Display relative path

print("Relative Path:", [Link](path))

Explanation:
[Link]() → Combines folder path and file name correctly.

[Link]() → Checks whether the file is available.

[Link]() → Displays the complete file path.

[Link]() → Displays the relative path of the file.

Sample Output:

Joined Path: Projects/[Link]

File exists

Absolute Path: C:\Users\Student\Projects\[Link]

Relative Path: Projects\[Link]

You might also like