Bird
Raised Fist0
Pythonprogramming~20 mins

Opening and closing files in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
File Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this file reading code?
Consider the following Python code that reads a file and prints its content. What will be printed?
Python
with open('test.txt', 'w') as f:
    f.write('Hello\nWorld')

with open('test.txt', 'r') as f:
    content = f.read()
print(content)
A
Hello
World
BHello World
C['Hello', 'World']
DError: file not found
Attempts:
2 left
💡 Hint
Remember that \n is a newline character and read() returns the whole content as a string.
Predict Output
intermediate
2:00remaining
What happens if you forget to close a file?
What will be the output or effect of this code snippet?
Python
f = open('sample.txt', 'w')
f.write('Data')
print('File written')
ANo output
BError: file not closed
CFile written
DData is not saved to file
Attempts:
2 left
💡 Hint
Think about what print() does and what happens if you don't close a file immediately.
Predict Output
advanced
2:00remaining
What is the output of this code using file context manager?
What will this code print?
Python
with open('numbers.txt', 'w') as f:
    for i in range(3):
        f.write(str(i))

with open('numbers.txt', 'r') as f:
    print(f.readline())
A0
BError: readline returns list
C1
D012
Attempts:
2 left
💡 Hint
readline() reads until the first newline or end of file.
Predict Output
advanced
2:00remaining
What error does this code raise?
What error will this code produce?
Python
f = open('nonexistent.txt', 'r')
content = f.read()
f.close()
AValueError
BFileNotFoundError
CTypeError
DNo error
Attempts:
2 left
💡 Hint
The file does not exist and is opened in read mode.
Predict Output
expert
3:00remaining
What is the value of 'lines' after this code runs?
Given this code, what is the value of the variable 'lines'?
Python
with open('data.txt', 'w') as f:
    f.write('line1\nline2\nline3')

with open('data.txt', 'r') as f:
    lines = f.readlines()

lines = [line.strip() for line in lines]
A['line1', 'line2', 'line3']
B['line1\n', 'line2\n', 'line3']
C['line1 line2 line3']
D['line1', 'line2', 'line3\n']
Attempts:
2 left
💡 Hint
readlines() returns lines with newline characters; strip() removes them.

Practice

(1/5)
1. What does the open() function do in Python when working with files?
easy
A. It opens a file and returns a file object to work with the file.
B. It closes a file that is currently open.
C. It deletes a file from the system.
D. It reads the entire content of a file automatically.

Solution

  1. Step 1: Understand the purpose of open()

    The open() function is used to open a file and create a file object that allows reading, writing, or other operations.
  2. Step 2: Differentiate from other file operations

    Closing a file is done with close(), deleting is done with other functions, and reading content requires calling methods on the file object.
  3. Final Answer:

    It opens a file and returns a file object to work with the file. -> Option A
  4. Quick Check:

    open() opens file [OK]
Hint: Remember: open() creates file object, close() ends it [OK]
Common Mistakes:
  • Confusing open() with close()
  • Thinking open() reads file content automatically
  • Assuming open() deletes files
2. Which of the following is the correct syntax to open a file named data.txt for reading in Python?
easy
A. file = open('data.txt', 'w')
B. file = open('data.txt', 'r')
C. file = open('data.txt', 'x')
D. file = open('data.txt', 'a')

Solution

  1. Step 1: Identify the mode for reading

    The mode 'r' stands for reading a file, which is the correct mode to open a file for reading.
  2. Step 2: Check other modes

    'w' is for writing (overwrites), 'x' is for creating a new file, 'a' is for appending to a file.
  3. Final Answer:

    file = open('data.txt', 'r') -> Option B
  4. Quick Check:

    Mode 'r' means read [OK]
Hint: Use 'r' mode to open files for reading [OK]
Common Mistakes:
  • Using 'w' mode which overwrites file
  • Using 'x' mode which fails if file exists
  • Using 'a' mode which appends instead of reading
3. What will be the output of the following code?
file = open('example.txt', 'w')
file.write('Hello')
file.close()
file = open('example.txt', 'r')
print(file.read())
file.close()
medium
A. '' (empty string)
B. example.txt
C. Hello
D. Error: file not found

Solution

  1. Step 1: Write 'Hello' to the file

    The file is opened in write mode, 'Hello' is written, then the file is closed to save changes.
  2. Step 2: Read the content back

    The file is reopened in read mode, and read() returns the string 'Hello' which is printed.
  3. Final Answer:

    Hello -> Option C
  4. Quick Check:

    Write then read returns written text [OK]
Hint: Write then close before reading to see content [OK]
Common Mistakes:
  • Not closing file before reading
  • Expecting filename as output
  • Assuming empty string without write
4. Identify the error in the following code snippet:
file = open('notes.txt', 'r')
content = file.read()
print(content)
file.write('More notes')
file.close()
medium
A. Trying to write to a file opened in read mode causes an error.
B. The file is not closed before reading.
C. The print statement is incorrect syntax.
D. The file name should be in double quotes.

Solution

  1. Step 1: Check file mode and operations

    The file is opened in 'r' (read) mode, which does not allow writing.
  2. Step 2: Identify the invalid operation

    Calling file.write() on a file opened for reading causes a runtime error.
  3. Final Answer:

    Trying to write to a file opened in read mode causes an error. -> Option A
  4. Quick Check:

    Write not allowed in 'r' mode [OK]
Hint: Write only in 'w' or 'a' modes, not 'r' [OK]
Common Mistakes:
  • Trying to write in read mode
  • Ignoring file close after reading
  • Thinking quotes style matters for filename
5. You want to safely read a file named log.txt and automatically close it after reading. Which code snippet correctly does this using Python's best practice?
hard
A. file = open('log.txt', 'r') content = file.read() file.close()
B. open('log.txt', 'r').read()
C. file = open('log.txt', 'r') content = file.read()
D. with open('log.txt', 'r') as file: content = file.read()

Solution

  1. Step 1: Understand safe file handling

    Using with statement ensures the file is automatically closed after the block finishes, even if errors occur.
  2. Step 2: Compare options

    file = open('log.txt', 'r') content = file.read() file.close() requires manual close, C misses close, D reads but does not save content or close explicitly.
  3. Final Answer:

    with open('log.txt', 'r') as file: content = file.read() -> Option D
  4. Quick Check:

    Use with statement for auto-close [OK]
Hint: Use with open(...) as file for automatic closing [OK]
Common Mistakes:
  • Forgetting to close file manually
  • Not using with statement for safety
  • Ignoring file object after open()