File Input / Output Flashcards
Outlines important commands for file input / output
What does the function call open(filename, mode = ‘r’ do?
Creates a file reference
What are the requirement for the command mode = ‘r’ to work properly?
File must exist, only inspect what is there
What does the command mode = ‘w’ do?
- Builds up new contents for a file
- saved at close()
- Will replace any previously existing file with same name when opened
- Creates new file when needed
What does the command mode = ‘a’ do?
- Same as writing but adds to existing contents (appends) rather than discarding existing contents
- Creates new file if needed
Which methods are allowed by mode = ‘r’ ?
- read
- readline
- readlines
Which methods are allowed by mode = ‘w’ or mode = ‘a’ ?
- write
- writelines
What does the close() function do?
Closes the file
What is a bookmark in this context?
Built in feature in Python that tracks where you are, updates as you go
What does the method call f.read(n) do?
Read up to n characters
What is the data type of the return value of f.read(n) ?
string
What is the purpose of the method call
f. read()?
read all remaining characters
What is the data type of the return value of f.read()?
string
What is the purpose of the method call f.readline(n)?
Read up to n characters on current line
What is the data type of the return value for f.readline(n)?
string
What is the purpose of the method call f.readline()
reads the rest of the current line
What is the data type of the return value of f.readline()?
string
What is the purpose of the method call
f. readlines()?
read all the remaining lines
What is the data type of the return value of f.readlines()?
A list of strings
What does the method call write(x) do?
Writes string x to a file
What does the method call writelines(xs) do?
Writes strings in list xs to a file
What must be done before a file can be written to in Python?
It must be closed.
What is calling the write() and writelines() function similar to?
Calling successive print calls, only the output goes to the file.
What are two things that are never added when the write() and writelines() method is called? What is the only thing that is added?
- No newlines or separators are ever added
- Only exactly what you write is added
What is reading files similar to?
Physically reading a book
What are the contents of a file similar to?
A python strig, indexed 0 and up