Problem Solving Using Python Assignment - 10: Submitted By: Submitted To
Problem Solving Using Python Assignment - 10: Submitted By: Submitted To
Problem Solving Using Python Assignment - 10: Submitted By: Submitted To
Assignment - 10
Submitted By:
Submitted To: Jashandeep Singh
Dr. Naveen Kumar Gupta Roll- 24104033
Group- B5b
Q1. Write a Python program to read an entire text file.
A: Code:
print(file.read())
A: Code:
lines = file.readlines()
n=3
for i in range(n):
print(lines[i], end="")
Q3. Write a Python program to append text to a file and display the text.
A: Code:
text = "hello22"
file = open("sample.txt", "a")
file.write(text)
file.close()
print(file.read())
file.close()
A: Code:
lines = file.readlines()
l = len(lines)
for i in range(n):
print(lines[l-i-1])
Q.5 Write a Python program to read a file line by line and store it into (a) a list, b) a
variable.
A: Code:
line = file.readline()
fileList = []
fileStr = ""
while line:
fileList.append(line)
fileStr += line
line = file.readline()
print(fileList)
print(fileStr)
Q.6 Write a Python program to count the number of lines in a text file.
A: Code:
lines = file.readlines()
print(len(lines))
Q.7 Write a Python program to copy the contents of a file to another file.
A: Code:
file1 = open("sample.txt", "r")
file2.write(file1.read())
Q8. Write a Python program that opens a text file named “data.txt” in binary read
mode, reads the contents, and prints them to the console. Enumerate the different
file modes available in Python (e.g., ‘r’, ‘w’, ’a’, ‘b’, ‘+’) and explain when you would
use each one.
A: Code:
print(file.read())
Q9. Write a Python program that uses the format operator (%) to insert values into a
string and print the resulting string to the console. Explain the purpose of the
format operator in Python and how it can be used to format output.
A: Code:
print(greeting % data)
Q10. Write a Python program that uses f-strings to insert values into a string and
print the resulting string to the console. Compare the use of the format operator
and f-strings for string formatting in Python, and discuss the advantages of using f-
strings
A: Code:
passwords = 10