Python Programming Exercises,
Gently Explained
27
fileObj.write('text goes here')
, which allows you to pass a string of text to write to the
file. Otherwise, in read mode calling fileObj.read() returns the file’s contents as a string.
Special Cases and Gotchas
If you open a file in write mode and the file doesn’t exist, then a blank file is created. If the file
does exist, it is overwritten with a blank file.
Append mode, as opposed to write mode,
adds text to
the end of the file without destroying the original content.
Now try to write a solution based on the information in the previous sections. If you still have
trouble solving this exercise,
read the Solution Template section for additional hints.
Solution Template
Try to first write a solution from scratch. But
if you have difficulty, you can use the following
partial program as a starting place.
Copy the following code from https://invpy.com/readwritefile-
template.py and paste it into your code editor. Replace the underscores with code to make a working
program:
def writeToFile(filename, text):
# Open the file in write mode:
with open(filename, ____) as fileObj:
# Write the text to the file:
____.write(text)
def appendToFile(filename, text):
# Open the file in append mode:
____ open(filename, ____) as fileObj:
# Write the text to the end of the file:
____.write(____)
def readFromFile(filename):
# Open the file in read mode:
____ ____(filename) as fileObj:
# Read all of the text in the file and return it as a string:
return ____.read()
The complete solution for this exercise is given in Appendix A and
https://invpy.com/readwritefile.py. You can view each step of this program as it
runs under a debugger at
https://invpy.com/readwritefile-debug/.
Dostları ilə paylaş: