Module 7 Flashcards
How do you open a file
open it: supply the name of the file stored on disk and the mode in which the file is to be opened
infile = open (“input.txt”, “r”)
opens the file for reading (indicated by the string argument “r”) and returns a file object that is associated with the name input.txt
all operations for accessing a file are made via what?
the file object
what are text files commonly used for?
to store information. The most “portable” type of data files
examples of text files that are created with a simple text editor
windows notepad, HTMML, and Python source code
What are some important things to keep in mind when opening a file for reading?
- the file must exist (and otherwise
be accessible) or an exception occurs - The file object returned by the open function must be saved in a
variable - All operations for accessing a file are made via the file object
file objects allows us to…
to use, access, and manipulate all the user accessible files.
outfile = open(“output.txt”, “w”)
To open a file for writing, you provide the name of the file as the first argument to the open function and the string “w” as the second argument
f the output file already exists, it is emptied before the new data is
written into it
If the file does not exist, an empty file is created
closing files
- When you are done processing a file, be sure to close the file using the close() method:
infile.close()
outfile.close()
- If your program exits without closing a file that was opened for
writing, some of the output may not be written to the disk file