File I/O
We can open a file using the built-in open function which returns a file object that can be read and
written to.
f = open("dummy.txt")
data = f.read()
f.close() The read method reads the entire file into a string. Files are opened in specific modes which
describe how the file is going to be used, the default mode is r for reading. The available
modes are:
| Mode | Usage |
|---|---|
r | Open for reading (default) |
w | Open for writing |
x | Create the file, failing if it already exists |
a | Append to the file if it already exists |
t | Parse file as text (default) |
b | Parse file as bytes |
+ | Open for updating |
We can also specify the encoding the default encoding is utf-8.
f = open("dummy.txt","r",encoding = "utf-8") Currently, we have to manually close the file, this is dangerous because the programming might stop
suddenly before the file closes, leaving open file handles. The with statement handles opening
and closing automatically.
with open("file.txt") as f:
f.read() File objects
The file object comes with a couple of methods regarding input and output:
| Method | Description |
|---|---|
read | Read the whole file as a string |
readline | Read and return one line from the file |
readlines | Read and return a list of lines from the file |
write | Write to the file |
For example you can iterate through the lines in a file using readlines
with open("file.txt") as f:
for line in f.readlines():
print(line)