Python Java SQL Course C C++ HTML CSS JS

Python Practice Questions

Topic-based coding problems with sample test cases — build confidence step by step.

Files Practice

1
Read and Display File Content
Easy
Write a program that opens a text file named "sample.txt", reads all its content, and prints it to the console.
The program uses a file named sample.txt that contains a few lines of text.
Print the entire content of sample.txt exactly as stored.
Sample Input 1
Hello
World
Sample Output 1
Hello
World
Sample Input 2
Python Practice
Line2
Sample Output 2
Python Practice
Line2
Sample Input 3
First
Second
Third
Sample Output 3
First
Second
Third
2
Count Lines in a File
Easy
Write a program that reads a text file named "data.txt" and counts the total number of lines in it.
The file data.txt already exists and contains some lines of text.
Print a single integer equal to the number of lines in data.txt.
Sample Input 1
line one
line two
line three
Sample Output 1
3
Sample Input 2
a
b
Sample Output 2
2
Sample Input 3
only one
Sample Output 3
1
3
Write Text to a File
Easy
Write a program that creates a new file named "output.txt" and writes the text "Hello, File!" into it.
No input is required by the program.
No console output. A file named output.txt containing Hello, File! should be created.
Sample Input 1

                      
Sample Output 1

                      
4
Read a Single Line From a File
Easy
Write a program that opens "greeting.txt" and prints only its first line.
The file greeting.txt exists and contains multiple lines.
Print the first line of greeting.txt.
Sample Input 1
Welcome to Python
Sample Output 1
Welcome to Python
Sample Input 2
Hello there
Everyone
Sample Output 2
Hello there
Sample Input 3
First line here
Sample Output 3
First line here
1
Append to a File
Medium
Write a program that opens "log.txt" in append mode and adds the line "Appended line" at the end without erasing existing content.
The file log.txt already exists and may contain text. The program appends a new line to it.
No console output. log.txt should contain its original content followed by Appended line.
Sample Input 1
old content
Sample Output 1
old content
Appended line
Sample Input 2
start
mid
Sample Output 2
start
mid
Appended line
2
Count Words in a File
Medium
Write a program that reads "story.txt" and prints the total number of words in it. Words are separated by spaces or newlines.
The file story.txt exists and contains one or more sentences.
Print a single integer equal to the word count.
Sample Input 1
hello world
Sample Output 1
2
Sample Input 2
one two three four
Sample Output 2
4
Sample Input 3
Python is fun
Sample Output 3
3
3
Read Numbers and Sum Them
Medium
Write a program that reads a file "nums.txt" where each line holds one integer, and prints the sum of all the integers.
The file nums.txt exists and each line contains a single integer.
Print the sum of all integers in nums.txt.
Sample Input 1
10
20
30
Sample Output 1
60
Sample Input 2
1
2
3
4
Sample Output 2
10
Sample Input 3
5
Sample Output 3
5
4
Copy File Content
Medium
Write a program that copies the content of "source.txt" into a new file "dest.txt" so that both files become identical.
The file source.txt exists and contains text.
No console output. dest.txt should exactly match source.txt after running.
Sample Input 1
copy me
Sample Output 1
copy me
Sample Input 2
lineA
lineB
Sample Output 2
lineA
lineB
1
Find the Longest Word in a File
Hard
Write a program that reads "text.txt" and prints the longest word found in it. If multiple words tie, print the first one encountered.
The file text.txt exists and contains words separated by spaces or newlines.
Print the longest word.
Sample Input 1
the quick brown fox
Sample Output 1
quick
Sample Input 2
alpha beta gamma
Sample Output 2
alpha
Sample Input 3
a bb ccc dd
Sample Output 3
ccc
2
Read and Reverse Every Line
Hard
Write a program that reads "input.txt", reverses the order of characters of each line, and writes the result to "reversed.txt".
The file input.txt exists and contains multiple lines.
No console output. reversed.txt should contain each line of input.txt reversed.
Sample Input 1
abc
def
Sample Output 1
cba
fed
Sample Input 2
hello
world
Sample Output 2
olleh
dlrow
Competitive MCQs — Files
Code snippets, output prediction, concepts & error spotting. Pick an answer to see instant feedback.
Score 0/ 32
Q1
Which function opens a file in Python?
Correct!
Wrong — correct answer is .
open(filename, mode) returns a file object.
Q2
Which mode opens a file for READING only?
Correct!
Wrong — correct answer is .
"r" is the default read mode; "w" truncates and writes.
Q3
Which mode opens a file for appending?
Correct!
Wrong — correct answer is .
Append mode "a" adds to the end without erasing content.
Q4
What is the output of this code?
python
1
2
3
f = open("data.txt", "r")
print(f.read())
f.close()
Correct!
Wrong — correct answer is .
read() without arguments reads the whole file.
Q5
What is the output of this code?
f = open("data.txt", "r")
print(f.read())
f.close()
Correct!
Wrong — correct answer is .
read() without arguments reads the whole file.
Q6
Which statement is the recommended way to ensure a file closes?
Correct!
Wrong — correct answer is .
The with statement automatically closes the file when the block ends.
Q7
What is the output of this code?
python
1
2
3
f = open("t.txt", "w")
f.write("Hello")
f.close()
Correct!
Wrong — correct answer is .
Write mode creates the file (or truncates) and writes "Hello".
Q8
What is the output of this code?
f = open("t.txt", "w")
f.write("Hello")
f.close()
Correct!
Wrong — correct answer is .
Write mode creates the file (or truncates) and writes "Hello".
Q9
Which method reads a file one line at a time?
Correct!
Wrong — correct answer is .
readline() reads one line; a file object is also iterable line-by-line.
Q10
Which mode opens a file for writing, but raises FileExistsError if it exists?
Correct!
Wrong — correct answer is .
Exclusive creation "x" fails if the file already exists.
Q11
What exception is raised when opening a missing file in "r" mode?
Correct!
Wrong — correct answer is .
Python 3 raises FileNotFoundError (a subclass of OSError).
Q12
What does the readlines() method return?
Correct!
Wrong — correct answer is .
readlines() returns a list where each element is one line.
Q13
Which mode opens a file for BOTH reading and writing without truncating?
Correct!
Wrong — correct answer is .
r+ opens an existing file for reading and writing at the current position.
Q14
What is the output of this code?
f = open("t.txt", "w")
f.write("A")
f.write("B")
f.close()
Correct!
Wrong — correct answer is .
Repeated writes append sequentially, so the file ends with "AB".
Q15
What does the with statement guarantee?
Correct!
Wrong — correct answer is .
Context managers close the resource automatically when the block exits.
Q16
What is the output of this code?
with open("t.txt", "w") as f:
f.write("Hi")
print(f.closed)
Correct!
Wrong — correct answer is .
After the with block, the file object is already closed, so f.closed is True.
Q17
Which method returns a list where each element is one line of the file?
Correct!
Wrong — correct answer is .
readlines() reads all lines into a list; readline() reads only one.
Q18
What does readline() return at the end of the file?
Correct!
Wrong — correct answer is .
readline() returns "" when there are no more lines to read.
Q19
Which mode would you use to add text to the end of an existing file?
Correct!
Wrong — correct answer is .
Append mode "a" preserves existing content and writes at the end.
Q20
What is the output of this code?
f = open("t.txt", "w")
f.write("12345")
f.close()
f = open("t.txt", "r")
print(f.read(3))
Correct!
Wrong — correct answer is .
read(3) reads up to three characters from the current position.
Q21
Which method returns the current file position?
Correct!
Wrong — correct answer is .
tell() reports how many bytes/characters have been read from the start.
Q22
Which method moves the file pointer to a given position?
Correct!
Wrong — correct answer is .
seek(offset) relocates the file pointer for subsequent reads/writes.
Q23
What is the output of this code?
f = open("t.txt", "w")
f.write("Hello")
f.close()
f = open("t.txt", "r")
print(f.readline())
Correct!
Wrong — correct answer is .
The file has one line, so readline() returns "Hello" (plus newline if written).
Q24
What does the "b" in mode "rb" mean?
Correct!
Wrong — correct answer is .
Binary mode reads bytes rather than decoding text.
Q25
What exception is raised when opening a file in "w" mode with an invalid path?
Correct!
Wrong — correct answer is .
Writing to a nonexistent directory raises FileNotFoundError.
Q26
What does os.remove("t.txt") do?
Correct!
Wrong — correct answer is .
os.remove() deletes the named file from the filesystem.
Q27
Which module lets you check whether a file exists?
Correct!
Wrong — correct answer is .
os.path.exists(path) returns True when the path is present.
Q28
What is the output of this code?
import os
print(os.path.exists("missing.txt"))
Correct!
Wrong — correct answer is .
The nonexistent file makes os.path.exists return False.
Q29
Which of these correctly reads an entire file?
Correct!
Wrong — correct answer is .
The with statement plus read() is the idiomatic way to load a whole file.
Q30
Which mode is dangerous because it silently truncates an existing file?
Correct!
Wrong — correct answer is .
Write mode "w" erases existing content the moment the file opens.
Q31
Which exception does Python raise when a file is used after close()?
Correct!
Wrong — correct answer is .
Operations on a closed file raise ValueError: I/O operation on closed file.
Q32
What is the difference between read() and readline()?
Correct!
Wrong — correct answer is .
read() without arguments returns the full remaining content; readline() returns one line.