Problem Solving Using Python Assignment - 10: Submitted By: Submitted To

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Problem Solving Using Python

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:

file = open("sample.txt", "r")

print(file.read())

Q2. Write a Python program to read first n lines of a file.

A: Code:

file = open("sample.txt", "r")

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()

file = open("sample.txt", "r")

print(file.read())

file.close()

Q.4 . Write a Python program to read last n lines of a file.

A: Code:

# Write a Python program to read last n lines of a file.

file = open("sample.txt", "r")

lines = file.readlines()

n = 3 #int(input("Type upto which line is to be printed: "))

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:

file = open("sample.txt", "r")

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:

file = open("sample.txt", "r")

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 = open("sample2.txt", "w")

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:

file = open("data.txt", "rb")

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:

greeting = "Hello, %s! . You have %d passwords saved."

data = ("Naveen Kumar", 8)

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:

name = "Naveen Kumar"

passwords = 10

print(f"Hello, {name}!. You have {passwords} passwords saved.")

You might also like