f = open('workfile', 'w', encoding="utf-8")
- The first argument is a string containing the filename.
- The second argument is another string containing a few characters describing the way in which the file will be used.
- mode can be
'r'when the file will only be read
'w'for only writing (an existing file with the same name will be erased)
- **It will delete the content first **
'a'opens the file for appending; any data written to the file is automatically added to the end (even when the file pointer is moved).
'r+'opens the file for both reading and writing. The mode argument is optional;
'r'will be assumed if it’s omitted.
a+will create a file if not exist
- mode can be
- The file pointer is at the beginning of the file by default
It is good practice to use the
with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using
with is also much shorter than writing equivalent
f.write(string) writes the contents of string to the file, returning the number of characters written.
f.readline() reads a single line from the file; a newline character (
\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.
This makes the return value unambiguous; if
f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by
'\n', a string containing only a single newline.