0% found this document useful (0 votes)
4 views13 pages

Python File Handling Solutions and Examples

The document provides solutions for Unit-5 of the Programming and Problem Solving (PPS) Question Bank, covering various file handling operations in Python. It includes explanations and examples for methods like tell(), seek(), file renaming, deletion, reading/writing data, and counting characters in files. Additionally, it discusses directory management and the differences between text and binary files.
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 views13 pages

Python File Handling Solutions and Examples

The document provides solutions for Unit-5 of the Programming and Problem Solving (PPS) Question Bank, covering various file handling operations in Python. It includes explanations and examples for methods like tell(), seek(), file renaming, deletion, reading/writing data, and counting characters in files. Additionally, it discusses directory management and the differences between text and binary files.
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

Here are the solutions for Unit-5 of the Programming and Problem Solving (PPS) Question

Bank. Since each question carries 6 marks, the theory answers include detailed explanations
with syntax and examples, and the programming solutions include complete logic with
comments.

Unit-5 Solutions

1.
[cite_start]Explain the tell() and seek() methods in file handling with suitable examples.

Answer:
In Python file handling, the file cursor (or file pointer) determines where reading or writing
commences.
●​ tell() Method:
○​ Purpose: This method returns the current position of the file pointer within the file.
The position is returned as an integer representing the number of bytes from the
beginning of the file.
○​ Syntax: file_object.tell()
●​ seek() Method:
○​ Purpose: This method is used to change the position of the file pointer to a specific
location.
○​ Syntax: file_object.seek(offset, whence)
■​ offset: Number of bytes to move.
■​ whence: The reference point (0 = beginning, 1 = current position, 2 = end of file).
Note: In text mode, only 0 is usually supported reliably.

Example:

Python

# Create a dummy file​


with open("[Link]", "w") as f:​
[Link]("Hello Python")​

# Reading and using seek/tell​
with open("[Link]", "r") as f:​
print([Link](5)) # Reads 'Hello', pointer is at 5​
print([Link]()) # Output: 5​
[Link](0) # Move pointer back to start​
print([Link](5)) # Reads 'Hello' again​

2. How can files be renamed and deleted in Python?


[cite_start]Explain with examples.

Answer:
Python uses the os module to perform operating system-dependent functionality, including
renaming and deleting files.
●​ Renaming a File:
○​ Function: [Link](current_name, new_name)
○​ Explanation: This function renames the file from current_name to new_name. If the
file does not exist, a FileNotFoundError is raised.
●​ Deleting a File:
○​ Function: [Link](filename)
○​ Explanation: This function deletes the file specified by filename. If the file is open or
doesn't exist, it may raise an error.

Example:

Python

import os​

# 1. Renaming a file​
# Assuming 'old_file.txt' exists​
try:​
[Link]("old_file.txt", "new_file.txt")​
print("File renamed successfully.")​
except FileNotFoundError:​
print("File not found.")​

# 2. Deleting a file​
try:​
[Link]("new_file.txt")​
print("File deleted successfully.")​
except FileNotFoundError:​
print("File does not exist.")​

3.
[cite_start]Write a Python program to count the number of vowels and consonants in a file.

Answer:

Python

def count_vowels_consonants(filename):​
vowels = "aeiouAEIOU"​
v_count = 0​
c_count = 0​

try:​
with open(filename, "r") as f:​
content = [Link]()​
for char in content:​
if [Link](): # Check if it's a letter​
if char in vowels:​
v_count += 1​
else:​
c_count += 1​
print(f"Total Vowels: {v_count}")​
print(f"Total Consonants: {c_count}")​

except FileNotFoundError:​
print("File not found.")​

# Usage​
# count_vowels_consonants("[Link]")​
4.
[cite_start]Write a Python program to count the number of tab characters (\t) and newline
characters (\n) present in a file.

Answer:

Python

def count_whitespace(filename):​
tab_count = 0​
newline_count = 0​

try:​
with open(filename, "r") as f:​
content = [Link]()​
for char in content:​
if char == '\t':​
tab_count += 1​
elif char == '\n':​
newline_count += 1​

print(f"Tab characters: {tab_count}")​
print(f"Newline characters: {newline_count}")​

except FileNotFoundError:​
print("File not found.")​

# Usage​
# count_whitespace("[Link]")​

5.
[cite_start]Write a Python program to copy the contents of one file into another file.

Answer:
Python

def copy_file(source_file, dest_file):​


try:​
# Open source in read mode and destination in write mode​
with open(source_file, "r") as src, open(dest_file, "w") as dest:​
content = [Link]()​
[Link](content)​
print(f"Contents copied from {source_file} to {dest_file} successfully.")​

except FileNotFoundError:​
print("Source file not found.")​

# Usage​
# copy_file("[Link]", "[Link]")​

6.
[cite_start]Explain the open() and close() functions in Python along with any 4 access modes.

Answer:
●​ open() Function: Used to open a file. It returns a file object.
○​ Syntax: file_object = open(file_name, access_mode)
●​ close() Function: Used to close an opened file to free up system resources.
○​ Syntax: file_object.close()
●​ Access Modes:
1.​ 'r' (Read Only): Opens a file for reading. The handle is positioned at the beginning.
Raises error if file doesn't exist.
2.​ 'w' (Write Only): Opens a file for writing. Overwrites the file if it exists or creates a
new one if it doesn't.
3.​ 'a' (Append): Opens a file for appending data. The pointer is at the end of the file.
Creates a new file if it doesn't exist.
4.​ 'r+' (Read and Write): Opens a file for both reading and writing. The pointer is
placed at the beginning.
7. What is a directory?
[cite_start]List and explain any four directory-related methods used in Python.

Answer:
A directory is a file system structure (folder) that contains references to other computer files
or directories. In Python, the os module handles directory operations.
Four Directory Methods:
1.​ [Link](): Returns the current working directory (CWD) as a string.
2.​ [Link](path): Creates a new directory named path. Raises an error if the directory
already exists.
3.​ [Link](path): Removes (deletes) an empty directory. If the directory is not empty, it
raises an error.
4.​ [Link](path): Returns a list of the names of the entries (files and folders) in the
directory given by path.

8. Write a Python program to: i. Display the current working directory ii. Create a
new directory iii.
[cite_start]Remove the created directory.

Answer:

Python

import os​

def manage_directory():​
# i. Display current working directory​
cwd = [Link]()​
print(f"Current Working Directory: {cwd}")​

dir_name = "TestDirectory"​

# ii. Create a new directory​
try:​
[Link](dir_name)​
print(f"Directory '{dir_name}' created successfully.")​
except FileExistsError:​
print(f"Directory '{dir_name}' already exists.")​

# iii. Remove the created directory​
# Note: Using input() just to pause so you can see the creation before deletion​
input("Press Enter to delete the directory...")​

try:​
[Link](dir_name)​
print(f"Directory '{dir_name}' removed successfully.")​
except FileNotFoundError:​
print("Directory not found.")​

# Usage​
# manage_directory()​

9.
[cite_start]Explain the different methods used to read and write data in a file in Python with
suitable examples.

Answer:
Read Methods:
1.​ read(size): Reads size bytes. If size is omitted, reads the entire file.
2.​ readline(): Reads a single line from the file.
3.​ readlines(): Reads all lines and returns them as a list of strings.

Write Methods:
1.​ write(string): Writes a string to the file. It does not add a newline automatically.
2.​ writelines(list): Writes a list of strings to the file.

Example:

Python

# Writing​
lines = ["Line 1\n", "Line 2\n"]​
with open("[Link]", "w") as f:​
[Link]("Header\n") # Using write()​
[Link](lines) # Using writelines()​

# Reading​
with open("[Link]", "r") as f:​
print([Link]()) # Reads 'Header\n'​
print([Link]()) # Reads remaining content​

10.
[cite_start]Write a Python program to count the number of lines, words, and characters in a
given file.

Answer:

Python

def file_stats(filename):​
try:​
with open(filename, "r") as f:​
lines = 0​
words = 0​
characters = 0​

for line in f:​
lines += 1​
characters += len(line)​
words += len([Link]()) # Splits by whitespace to find words​

print(f"Lines: {lines}")​
print(f"Words: {words}")​
print(f"Characters: {characters}")​

except FileNotFoundError:​
print("File not found.")​

# Usage​
# file_stats("[Link]")​
11.
[cite_start]Write a Python program to search for a specific word in a file.

Answer:

Python

def search_word(filename, target_word):​


found = False​
line_num = 0​

try:​
with open(filename, "r") as f:​
for line in f:​
line_num += 1​
if target_word in line:​
print(f"Word '{target_word}' found on line {line_num}")​
found = True​

if not found:​
print("Word not found in the file.")​

except FileNotFoundError:​
print("File not found.")​

# Usage​
# search_word("[Link]", "Python")​

12.
[cite_start]Write a Python program to count the number of uppercase and lowercase
characters in a file.
Answer:

Python

def count_case(filename):​
upper_count = 0​
lower_count = 0​

try:​
with open(filename, "r") as f:​
content = [Link]()​
for char in content:​
if [Link]():​
upper_count += 1​
elif [Link]():​
lower_count += 1​

print(f"Uppercase characters: {upper_count}")​
print(f"Lowercase characters: {lower_count}")​

except FileNotFoundError:​
print("File not found.")​

# Usage​
# count_case("[Link]")​

13. Why are files required in Python?


[cite_start]Explain absolute path and relative path with examples.

Answer:
●​ Need for Files:
1.​ Persistence: Data stored in variables is volatile (lost when the program ends). Files
allow data to be saved permanently on the disk.
2.​ Portability: Files allow easy transfer of data between different programs or
computers.
3.​ Large Data: Files can store large amounts of data that might not fit entirely in the
computer's RAM.
●​ File Paths:
○​ Absolute Path: The full path starting from the root directory of the file system. It is
independent of the current working directory.
■​ Example (Windows): C:\Users\Student\Documents\Project\[Link]
■​ Example (Linux/Mac): /home/user/project/[Link]
○​ Relative Path: The path relative to the directory where the Python script is currently
running.
■​ Example: If the script is in C:\Users\Student\, the relative path to the file above is
Documents\Project\[Link].

14.
[cite_start]Write a Python program that counts the occurrences of tab space and newline
characters present in a file.

(Note: This is identical to Question 4. The solution is provided again below).

Answer:

Python

def count_tabs_newlines(filename):​
tabs = 0​
newlines = 0​
try:​
with open(filename, "r") as f:​
text = [Link]()​
tabs = [Link]('\t')​
newlines = [Link]('\n')​
print(f"Tabs: {tabs}, Newlines: {newlines}")​
except FileNotFoundError:​
print("File not found.")​

15. Differentiate between text files and binary files.


[cite_start]Explain any four file access modes used in Python.
Answer:
●​ Difference between Text and Binary Files:
○​ Text Files: Store data as characters (strings). They are human-readable (e.g., .txt,
.py, .csv). Newline characters might be translated automatically by Python.
○​ Binary Files: Store data in bytes (0s and 1s). They are not human-readable directly
and are used for images, audio, video, or compiled code (e.g., .jpg, .mp3, .exe). No
automatic translation of EOL characters occurs.
●​ Four File Access Modes:
1.​ 'r' (Read): Opens for reading. Default mode.
2.​ 'w' (Write): Opens for writing, truncating the file first.
3.​ 'a' (Append): Opens for writing, appending to the end of the file.
4.​ 'rb' (Read Binary): Opens a file for reading in binary format (crucial for non-text
files).

16.
[cite_start]Write a Python program to count the number of digits and spaces in a file.

Answer:

Python

def count_digits_spaces(filename):​
digits = 0​
spaces = 0​

try:​
with open(filename, "r") as f:​
content = [Link]()​
for char in content:​
if [Link]():​
digits += 1​
elif char == ' ':​
spaces += 1​

print(f"Total Digits: {digits}")​
print(f"Total Spaces: {spaces}")​

except FileNotFoundError:​
print("File not found.")​

# Usage​
# count_digits_spaces("[Link]")​

You might also like