Introduction
To interact with any type of file, we first need to know a bit about some general functions. open(file, mode='r',...)
is the first, and is used to open a file. Using the parameter mode, we can here choose how the file is to be opened, as well as what we are able to do with it. The following table is taken from docs.python.org.
Character | Meaning |
---|---|
'r' | open for reading (default) |
'w' | open for writing, truncating1 the file first |
'x' | open for exclusive creation, failing if the file already exists |
'a' | open for writing, appending to the end of the file if it exists |
'b' | binary mode |
't' | text mode (default) |
'+' | open for updating (reading and writing) |
1Means removing the file contents without deleting the file.
It is also important to close the file after we are done with it, which we will show in the following examples. If you are unsure why it is important to close the file, please have a look at this post on Stack Overflow discussing the topic.
Textfile [.txt]
Textf