Unit - IV (Important Questions and Answers)
1. Explain all the file handling modes with an example program in Python?
(OR)
Explain the file modes with an example program in Python?
(OR)
Explain the modes with an example program in Python?
Different File Mode in Python
Mode Description Example Program
Read-only. Raises I/O error if file with open('[Link]', 'r') as file:
‘r’
doesn't exist. content = [Link]()
with open('[Link]', 'r+') as file:
Read and write. Raises I/O error if
‘r+’ content = [Link]()
the file does not exist.
[Link]('\nThis is a new line.')
Write-only. Overwrites file if it with open('[Link]', 'w') as file:
‘w’
exists, else creates a new one. [Link]('Hello, world!')
with open('[Link]', 'w+') as file:
Read and write. Overwrites file or [Link]('Hello, world!')
‘w+’
creates new one. [Link](0)
content = [Link]()
Append-only. Adds data to end. with open('[Link]', 'a') as file:
‘a’
Creates file if it doesn't exist. [Link]('\nThis is a new line.')
with open('[Link]', "a+") as file:
[Link]("Write the content to file.\n")
Read and append. Pointer at end.
‘a+’ [Link](0)
Creates file if it doesn't exist.
content = [Link]()
print(content)
with open('[Link]', 'rb') as file:
‘rb’ Read in binary mode. File must exist.
data = [Link]()
Read and write in binary mode. File
‘rb+’
must exist.
Write in binary. Overwrites or creates with open("[Link]", "wb") as file:
‘wb’
new. [Link](b"Some raw binary data.")
Read and write in binary. Overwrites
‘wb+’
or creates new.
with open("[Link]", "wb") as f:
[Link](b"Hello") # Initial content
# Open file in 'ab' mode (append binary)
with open("[Link]", "ab") as f:
[Link](b" World") # Append bytes at the
Append in binary. Creates file if not end
‘ab’
exist.
# Read the file to verify
with open("[Link]", "rb") as f:
content = [Link]()
print("File content after append:",
content)
Read and append in binary. Creates
‘ab+’
file if it does not exist.
2. Explain the file handling built-in functions in Python?
(OR)
Explain the file handling methods in Python?
(OR)
Explain the built-in functions of file handling in Python?
(OR)
Explain the built-in functions and methods for handling files in Python with an example
program?
(OR)
Explain the built-in functions and methods of file handling in Python with an example
program?
Built-in Functions for File Handling or File Handling Methods in Python
Functions Description Example Program
open( ) open( ) function is used to file = open('[Link]', 'r')
open a file in Python, [Link]()
which takes the file name
and the mode of operation
as arguments.
file = open('[Link]', 'r')
read( ) function is used to content = [Link]( )
read(size)
read entire as string. print(content)
[Link]()
file = open('[Link]', 'r')
readline( ) function is used content = [Link]( )
readline( ) to read single line from
file. print(content)
[Link]()
file = open('[Link]', 'r')
readlines( ) function is content = [Link]( )
readlines( ) used to read all lines from
file and displayed in list. print(content)
[Link]()
write( ) function is used to file = open(‘[Link]', "w")
write(string) write a string of data to a [Link]("Hello")
file. [Link]()
lines = ["First line\n", "Second line\n"]
writelines( ) function is file = open('[Link]', "w")
writelines(list_of_strings) used to write a list of
strings to a file. [Link](lines)
[Link]()
close() method is used to file = open('[Link]', 'r')
close( )
close the file manually [Link]()
'with' statement is used to with open(‘[Link]’, "r") as f:
‘with' statement safely open and close files data = [Link]()
automatically.
with open('[Link]', "w") as file:
print("Position at start:", [Link]())
Returns current file
tell( )
pointer or cursor position. [Link]("Hello")
print("Position after writing 'Hello':",
[Link]())
seek(offset, whence) Moves file pointer or with open('[Link]', "w") as f:
cursor to a new location. [Link]("Hello, World!")
with open('[Link]', "r") as f:
print("Full content:", [Link]())
[Link](0)
print("Pointer moved back to:",
[Link]())
[Link](7)
print("Pointer moved to position 7:",
[Link]())
import time
with open('[Link]', "w") as file:
[Link]("Writing data...")
[Link]()
Force writing the buffer to print("Data flushed to file!")
flush( )
disk.
[Link](2)
[Link]("\nMore data written
later.")
[Link]()
print("Second flush completed.")
with open('[Link]', "w") as f:
[Link]("Hello, World!")
with open('[Link]', "r+") as f:
print("Original content:", [Link]())
# Move file pointer to start
Resize a file to a given
truncate(size) [Link](0)
length.
# Truncate file to 5 bytes
[Link](5)
# Read the truncated file
with open('[Link]', "r") as f:
print("After truncation:", [Link]())
File Management Functions using the os module
[Link](current_name,
Renames a file.
new_name)
[Link](filename) or
Deletes a file.
[Link](filename)
Checks if a file or
[Link](filename)
directory exists.
[Link](directory_name) Creates a new directory.
3. Explain file pointer with an example program in Python?
(OR)
Explain how manipulating file pointer with an example program in Python?
(OR)
Can you explain, with an example program in Python, how to set up a pointer (like a
cursor) to keep track of where you are in the file?
(OR)
Explain how to set up a pointer (like a cursor) to keep track of where you are in the file
with an example program in Python?
(OR)
Explain how to set up a cursor to keep track of where you are in the file with an example
program in Python?
(OR)
Can you explain seek() and tell() file handling with an example program in Python?
In Python, we can set up a pointer or cursor to track where you are in a file using:
tell() → tells the current cursor position
seek() → moves the cursor to a given position
Syntax for tell():
file_object.tell()
Parameters: It takes no parameters.
Return Value: An integer representing the current position of the file pointer.
Syntax for seek():
file_object.seek(offset, whence)
Parameters:
offset: The number of bytes to move the file pointer. This can be a positive or negative integer.
whence (optional): The reference point from which the offset is calculated. It defaults to 0
(beginning of the file). You can also use the constants from the os module (os.SEEK_SET,
os.SEEK_CUR, os.SEEK_END).
0 or os.SEEK_SET: Move relative to the beginning of the file (default).
1 or os.SEEK_CUR: Move relative to the current position of the file pointer.
2 or os.SEEK_END: Move relative to the end of the file.
Example Program:
# Create a sample file
with open("[Link]", "w") as f:
[Link]("Hello\n")
[Link]("File pointer example.\n")
[Link]("Python")
# Read and track the file pointer
with open("[Link]", "r") as f:
print("Initial cursor position:", [Link]()) # Should be 0
# Read first 5 characters
data = [Link](5)
print("Read:", data)
print("Cursor after reading 5 chars:", [Link]())
# Move cursor to beginning of second line
[Link](13) # Move to byte 13 (after "Hello World!\n")
print("Cursor moved to:", [Link]())
# Read the next line
line = [Link]()
print("Read using readline():", [Link]())
print("Cursor after readline():", [Link]())
# Jump to end of file
[Link](0, 2) # 0 offset, 2 = end of file
print("Cursor at end of file:", [Link]())
4. Explain generator with an example program in Python?
A generator is a special type of function that uses the ‘yield’ keyword instead of ‘return’.
‘return’ ends the function.
‘yield’ pauses the function and saves its state.
When the generator is called again, it resumes from where it left off.
Generator returns values one at a time, saves memory and faster for large data.
Example Program:
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
Output:
1
2
3
5. Write a program to reverse the contents of a file character by character, separating each
character with a comma.
(OR)
Construct a program to change the contents of the file by reversing each character
separated by comma:
Suppose the following input is supplied to the file:
Hello
Then, the output of the file should be:
o,l,l,e,H
Answer:
# Open the file ‘[Link]’ in read mode
with open("[Link]", "r") as file:
content = [Link]().strip()
# Reverse the content
reversed_content = content[::-1]
# Join each character with a comma
formatted_output = ",".join(reversed_content)
# Write to another file named ‘[Link]’
with open("C:/Users/Main/Desktop/Python Files/[Link]", "w") as file:
[Link](formatted_output)
# Print the output
print(formatted_output)
# Close the file
[Link]()
6. There is a file named [Link]. Enter some positive number into the file named [Link].
Read the content of the file and if the number is an odd number, write it to [Link] and if
the number is even, write it to [Link]
Answer:
file = open('C:/Users/Main/Desktop/Python Files/even_odd.txt',"rt")
for item in file:
if [Link]:
num = int(item)
if (num % 2 == 0):
even = open('C:/Users/Main/Desktop/Python Files/[Link]',"a")
[Link](str(num))
[Link]("\n")
else:
odd = open('C:/Users/Main/Desktop/Python Files/[Link]',"a")
[Link](str(num))
[Link]("\n")
7. Construct a program which accepts a sequence of words separated by whitespace as file
input. Print the words composed of digits only.
Answer:
# Read the input from a file ([Link])
with open("[Link]", "r", encoding="utf-8") as f:
content = [Link]().split()
# Print words composed only of digits
for word in content:
if [Link]():
print(word)
8. Construct a program to read a file and capitalize the first letter of every word in the file.
Answer:
with open("[Link]", "r") as f:
data = [Link]()
# Capitalize the first letter of every word
result = [Link]()
with open("C:/Users/Main/Desktop/Python Files/[Link]", "w") as f:
[Link](result)
9. Construct a program to read a file named "[Link]" and count the number of lines,
words, and characters in the file.
Answer:
def count_file_stats(filename):
lines = 0
words = 0
characters = 0
with open(filename, "r") as file:
for line in file:
lines += 1
characters += len(line)
words += len([Link]())
return lines, words, characters
# File name
filename = '[Link]'
# Get counts
line_count, word_count, char_count = count_file_stats(filename)
print("Number of lines:", line_count)
print("Number of words:", word_count)
print("Number of characters:", char_count)
10. Open a file for writing and insert the following records into the file:
apple
orange
pear
Construct a program to strip or remove any white or trailing spaces and newline.
The result should be:
apple
orange
pear
Answer:
# Open file for writing and insert records
with open("[Link]", "w") as file:
[Link]("apple\n")
[Link]("orange\n")
[Link]("pear\n")
# Open the same file for reading and remove whitespace/newlines
with open("[Link]", "r") as file:
lines = [Link]()
print(lines)
# Strip whitespace and newlines
cleaned_lines = [[Link]() for line in lines]
# Display the cleaned result
for fruit in cleaned_lines:
print(fruit)
11. Construct a program Change all the numbers in the file to text.
Construct a program for the same.
Example:
Given 2 integer numbers, return their product only if the product is equal to or lower than
10.
And the result should be:
Given two integer numbers, return their product only if the product is equal to or lower
than one zero.
Answer:
# Mapping of digits to their word equivalents
digit_to_word = {
"0": "zero",
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine"
def convert_digits_to_words(text):
result = ""
for ch in text:
if [Link](): # if the character is 0–9
result += digit_to_word[ch] + " "
else:
result += ch
return [Link](" ", " ") # clean extra spaces
# ---- MAIN PROGRAM ----
# Read the original file
with open('[Link]', "r") as file:
content = [Link]()
# Convert the digits in the text
converted = convert_digits_to_words(content)
# Save result to a new file
with open('ABC_Converted.txt', "w") as file:
[Link](converted)
print("Conversion complete! Check ABC_converted.txt")
12. Construct a program to read a CSV file and display the rows where a specific column
value exceeds a given threshold.
Answer:
import csv
def filter_csv_by_threshold(filename, column_name, threshold):
with open(filename, newline='', encoding='utf-8') as csvfile:
reader = [Link](csvfile)
print(f"Rows where '{column_name}' exceeds {threshold}:")
for row in reader:
try:
value = float(row[column_name])
if value > threshold:
print(row)
except ValueError:
# Skip rows where the value cannot be converted to a number
continue
# Example usage:
filter_csv_by_threshold('[Link]', "price", 200.0)
Here is a sample "[Link]" file you can create for testing:
item,category,price,quantity
apple,fruit,50.0,10
banana,fruit,120.5,5
orange,fruit,80.0,20
grape,fruit,210.0,15
carrot,vegetable,45.0,30
melon,fruit,abc,5
pineapple,fruit,150.0,8