pp-week-8
pp-week-8
Week 9
escription:This program uses the random module togenerate random numbers and writes
D
E7
them to a file named random_numbers.txt. The numbers are written line by line, ensuring each
number is stored separately for easy retrieval.
Program:
import random
for _ in range(20):
number = random.randint(1, 100)
file.write(str(number) + "\n")
05
with open("random_numbers.txt", "w") as file:
1A
print("20 random numbers have been written to 'random_numbers.txt'")
Output:
33
3
2
87
56
12
98
23
...
Inference:Writing random numbers to a file mightseem simple, but it’s an essential step in
working with file handling.Open method in python can also be used but the choice to use with
open comes from the intuition to have code written in more pythonic way (as with open will
automatically close the file).A separate with open statement can be written to read to the
contents in file as well.
rogram 2: Demonstrating seek(), tell(), and flush()
P
Methods
Aim:To illustrate the usage of seek(), tell(), andflush() methods for file pointer manipulation.
escription:The program writes data to a file anddemonstrates how to move the file pointer
D
using seek(), retrieve the current position using tell(), and forcefully write buffered data using
flush().
Program:
E7
with open("example.txt", "w") as file:
file.write("Hello, this is a test file.")
file.flush()
content = file.read(5)
print("Read content:", content)
print("Current Position:", file.tell())
05
print("After seek(7), Position:", file.tell())
1A
Output:
Initial Position: 0
After seek(7), Position: 7
33
Inference:The seek() and tell() functions make navigatinga file much easier, which is useful
23
when working with large files or when we need to edit specific portions of data. The flush()
function ensures that data is saved immediately, which is especially helpful in real-time
applications. These methods help us manage file operations more efficientl
rogram 3: Demonstrating read(), readline(), and
P
readlines() Methods
Aim:To illustrate different file reading methods:read(), readline(), and readlines().
escription:This program writes multiple lines toa file and demonstrates how different reading
D
methods retrieve data in various ways.
Program:
with open("sample.txt", "w") as file:
E7
file.write("Line 1: Hello World!\n")
file.write("Line 2: Python is great.\n")
file.write("Line 3: File handling is useful.\n")
Output:
33
sing read():
U
Line 1: Hel
sing readline():
U
23
sing readlines():
U
['Line 1: Hello World!\n', 'Line 2: Python is great.\n', 'Line 3: File handling is useful.\n']
Inference:Reading files is one of the most commontasks in programming, and Python gives us
different ways to do it. The read() method is useful when we need to fetch a specific number of
characters, readline() helps when we only want a single line, and readlines() makes it easy to
grab everything at once. Knowing when to use each of these makes working with files much
more efficient.