CDT Ch 1 Practice Exam 4 Questions &
Answers 2024/2025
error handling - ANSWERSIf an error occurs while opening or operating on a file, an IOError will be
raised. Therefore, we can apply the try and except pattern on the open function as well:
>>> try:
>>> for line in open('fake_file_that_does_not_exist'):
>>> print line.strip()
>>> except IOError as e:
>>> print 'Unable to open file:', e
Unable to open file: [Errno 2] No such file or directory: 'fake_file_that_does_not_exist'
with statement - ANSWERSSince it can be cumbersome to have to open and close a file manually, you
can use Python's with statement:
>>> with open('data.txt', 'w') as fh:
fh.write('hello, data file!\n')
>>> open('data.txt').read()
'hello, data file!\n'
Using the with statement, the file is opened and bound to the fh variable and we can use it inside the
body of the with statement. Once we leave the with block, the file will automatically be closed for us.
What are the four basic operations you can perform on a file (handle)? - ANSWERSThere are four basic
operations you can do to a file: open, read, write, and close. The open() function returns a File object.
The read() methods returns tha string that is stored in the file. The write() funtion allws you to write
content (similar to the way the print() function writes strings to a screen. The close() function closes the
file.
file - ANSWERSa sequence of bytes
File Handle - ANSWERS> an object that represents the file.
The benefits of buying summaries with Stuvia:
Guaranteed quality through customer reviews
Stuvia customers have reviewed more than 700,000 summaries. This how you know that you are buying the best documents.
Quick and easy check-out
You can quickly pay through credit card or Stuvia-credit for the summaries. There is no membership needed.
Focus on what matters
Your fellow students write the study notes themselves, which is why the documents are always reliable and up-to-date. This ensures you quickly get to the core!
Frequently asked questions
What do I get when I buy this document?
You get a PDF, available immediately after your purchase. The purchased document is accessible anytime, anywhere and indefinitely through your profile.
Satisfaction guarantee: how does it work?
Our satisfaction guarantee ensures that you always find a study document that suits you well. You fill out a form, and our customer service team takes care of the rest.
Who am I buying these notes from?
Stuvia is a marketplace, so you are not buying this document from us, but from seller Bensuda. Stuvia facilitates payment to the seller.
Will I be stuck with a subscription?
No, you only buy these notes for $7.99. You're not tied to anything after your purchase.