0
0
Pythonprogramming~5 mins

Opening and closing files in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the open() function in Python?
The open() function is used to open a file so you can read from it, write to it, or both. It returns a file object that you can work with.
Click to reveal answer
beginner
What does the mode parameter in open(filename, mode) specify?
The mode parameter tells Python how you want to use the file: <br> - 'r' for reading <br> - 'w' for writing (overwrites file) <br> - 'a' for appending (adding to the end) <br> - 'b' for binary mode <br> - You can combine modes like 'rb' for reading binary files.
Click to reveal answer
beginner
Why is it important to close a file after opening it?
Closing a file frees up system resources and ensures that all data is properly saved and written. If you don't close a file, changes might not be saved and the file can stay locked.
Click to reveal answer
beginner
How do you properly close a file in Python?
You call the close() method on the file object, like file.close(). This tells Python you are done working with the file.
Click to reveal answer
intermediate
What is the advantage of using the with statement when working with files?
Using with open(filename) as file: automatically closes the file when the block ends, even if errors happen. This makes your code safer and cleaner.
Click to reveal answer
Which mode should you use to open a file for reading only?
A'w'
B'r'
C'a'
D'x'
What happens if you open a file in 'w' mode and the file already exists?
AThe file is opened and content is preserved
BThe file is deleted and recreated empty
CAn error is raised
DThe file is opened and existing content is erased
Which method do you call to close a file?
Aclose()
Bend()
Cstop()
Dfinish()
What is the benefit of using with open() instead of just open()?
AIt automatically closes the file after use
BIt opens the file faster
CIt prevents the file from being read
DIt locks the file permanently
If you want to add text to the end of an existing file without deleting its content, which mode do you use?
A'r'
B'w'
C'a'
D'x'
Explain how to open a file for reading and then close it properly in Python.
Think about the steps: open, use, then close.
You got /4 concepts.
    Describe the advantages of using the with statement when working with files.
    Why is 'with' safer than just open()?
    You got /4 concepts.