Reading and Writing Files (I/O) Flashcards
This the basic methods for read and writing to files in Python
fileObject.close() Method
Closes the file. Like Files->Save.. in your editor
fileObject.read() Method
Reads the contents of the file. You can assign the result to a variable
fileObject.readline() Method
Reads just one line of text file.
fileObject.truncate() Method
Empties the file. Watch out if you care about the file.
fileObject.write(stuff) Method
Writes stuff to the file.
open(filename, access_mode)
returns a file object in the specified mode(read, write), defaults to read, append, etc)
note: list of the methods can be found in pydoc file
file access mode ‘r’
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
file access mode ‘rb’
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
file access mode ‘r+’
Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
file access mode ‘rb+’
Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
file access mode ‘w’
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
file access mode ‘wb’
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
file access mode ‘w+’
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
file access mode ‘wb+’
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
file access mode ‘a’
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.