Quiz: Python file handling and exceptions

This quiz covers essential concepts of Python file handling and exception management, focusing on practical applications and common scenarios.

CharlotteBrown7t·24 flashcards·24 questions
collegecomputer_scienceprogramming
0
Known
1 / 24
0
Learning
Front

What is file handling in Python?

Tap to flip
Back

File handling refers to the process of creating, reading, updating, and deleting files in Python using built-in functions.

Tap to flip
Got it
Still learning

Quiz(24 questions)

Question 1 of 24

1. What does the 'with' statement ensure when opening files in Python?

Terms in this Study Set(24)

Flashcards 1(12)

What is file handling in Python?

File handling refers to the process of creating, reading, updating, and deleting files in Python using built-in functions.

How do you open a file in Python?

Use the built-in function `open(filename, mode)` where mode can be 'r', 'w', 'a', etc.

True or False: 'r' mode overwrites a file.

False. 'r' mode opens a file for reading only; it cannot overwrite.

Fill in the blank: To close a file, use the method ______.

.close()

What is the purpose of exceptions in Python?

Exceptions allow handling errors gracefully, preventing program crashes and managing unexpected situations.

What is the 'with' statement used for?

The 'with' statement simplifies file handling by automatically closing the file after the block is executed.

Compare 'w' and 'a' modes.

'w': Write mode, overwrites existing files. 'a': Append mode, adds to existing files.

Cause → Effect: What happens when you try to open a non-existent file in 'r' mode?

An IOError is raised, indicating the file cannot be found.

How do you read contents of a file?

Use `file.read()` to read all contents or `file.readline()` for one line at a time.

What is a try-except block?

A try-except block is used to catch and handle exceptions in Python, providing a way to respond to errors.

What does the 'finally' block do?

The 'finally' block executes code regardless of whether an exception was raised, often used for cleanup.

How to write data to a file?

Open a file in 'w' or 'a' mode, then use `file.write(data)` to write the desired content.

Flashcards 2(12)

What does 'with open' do in Python?

Automatically handles opening and closing files. - Ensures files are properly closed, even if an error occurs.

True or False: Exceptions crash the program.

False - Exceptions can be caught and handled using try-except blocks.

List two built-in exceptions in Python.

1. ValueError 2. FileNotFoundError

Fill in the blank: To read a file, use ______.

file.read()

How to handle multiple exceptions?

Use a tuple in the except clause: try: ... except (TypeError, ValueError): ...

What is the purpose of 'finally'?

'finally' block always executes after try-except, regardless of exceptions, for cleanup actions.

Compare 'read()' vs 'readline()'.

'read()' reads the entire file; 'readline()' reads one line at a time.

Cause → Effect: FileNotFoundError occurs when...

...you try to open a file that does not exist.

Example: Write to a file in Python.

with open('output.txt', 'w') as file: file.write('Hello, World!')

What is a context manager?

A construct that simplifies resource management, ensuring resources are properly managed.

True or False: You must manually close a file opened with 'with'.

False - 'with' automatically closes the file.

Describe the role of 'try' in error handling.

'try' block allows you to test a block of code for errors, catching exceptions.

Questions in this Study Set(24)

1. What does the 'with' statement ensure when opening files in Python?

A.It automatically manages file closure.
B.It allows multiple files to be opened simultaneously.
C.It converts file contents to a list.
D.It requires manual file closure.

2. What does the 'a' mode do when opening a file in Python?

A.Appends data to the end of the file
B.Overwrites the file
C.Reads the file
D.Creates a new file only

3. True or False: The try block can contain multiple statements.

A.True
B.False
C.Only one statement can be inside.
D.It can only handle one exception.

4. Which statement correctly describes the purpose of exceptions in Python?

A.To enhance performance
B.To improve code readability
C.To handle errors gracefully
D.To format data

5. Which of the following is NOT a built-in exception in Python?

A.KeyError
B.TypeError
C.FileError
D.IndexError

6. What happens if you try to read from a closed file?

A.The file is reopened automatically
B.An error is raised
C.The contents are returned as empty
D.The program continues without issues

7. What does the 'write()' method do?

A.It reads data from a file.
B.It creates a new file.
C.It writes data to a file.
D.It appends data to a file.

8. Which of the following is NOT a valid mode for opening a file in Python?

A.r
B.w
C.a
D.d

9. How can you handle multiple specific exceptions in one line?

A.using separate except clauses for each exception
B.using a list in the except clause
C.using a tuple in the except clause
D.using a dictionary in the except clause

10. When using the 'with' statement for file handling, what is its main advantage?

A.It increases file size
B.It automatically handles exceptions
C.It ensures files are closed properly
D.It improves file read speed

11. What happens if you do not catch an exception in Python?

A.The program will terminate.
B.The exception will be logged.
C.The program will continue without issues.
D.The exception will be ignored.

12. How can you write multiple lines to a file in Python?

A.Using file.write() for each line
B.Using file.add() method
C.Using file.append() method
D.Using file.write_all() method

13. What is the primary role of the 'finally' block?

A.To catch exceptions.
B.To execute cleanup actions.
C.To define variables.
D.To manage memory.

14. What does the 'finally' block in a try-except structure do?

A.It executes code only if there is an exception
B.It is optional and can be omitted
C.It ensures that certain code runs regardless of exceptions
D.It defines the main code to execute

15. Which method reads the entire content of a file at once?

A.read()
B.readline()
C.readlines()
D.seek()

16. How do you read a single line from a file in Python?

A.Use file.getline()
B.Use file.read() with an argument
C.Use file.readline()
D.Use file.read_line()

17. Fill in the blank: To open a file for reading, you use 'open(filename, ____)'.

A.'r'
B.'w'
C.'a'
D.'x'

18. What is the effect of opening a file in 'w' mode?

A.The file is opened for reading only
B.The file is created if it doesn't exist
C.The file is opened for both reading and writing
D.The file is permanently deleted

19. What does the exception FileNotFoundError indicate?

A.The file is empty.
B.The file path is incorrect.
C.The file is not accessible.
D.The file cannot be written to.

20. What kind of error is raised if you attempt to open a non-existent file in 'r' mode?

A.ValueError
B.FileNotFoundError
C.IOError
D.PermissionError

21. Which of the following correctly demonstrates writing to a file safely?

A.open('data.txt', 'w') as f: f.write('Hello')
B.with open('data.txt', 'w') as f: f.write('Hello')
C.write('Hello', 'data.txt')
D.f = open('data.txt', 'w'); f.write('Hello')

22. Which method is used to close an open file in Python?

A.file.end()
B.file.close()
C.file.quit()
D.file.stop()

23. What is a context manager primarily used for?

A.Handling exceptions.
B.Managing file operations.
C.Creating variables.
D.Performing calculations.

24. How can you handle an exception that occurs during file operations?

A.By using a try-except block
B.By ignoring the error
C.By restarting the program
D.By using a print statement

Related Study Sets

Create Your Own Study Set

Upload a PDF, paste your notes, or describe a topic – AI generates flashcards, quizzes and more in seconds.