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:

ModeUsage
rOpen for reading (default)
wOpen for writing
xCreate the file, failing if it already exists
aAppend to the file if it already exists
tParse file as text (default)
bParse 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:

MethodDescription
readRead the whole file as a string
readlineRead and return one line from the file
readlinesRead and return a list of lines from the file
writeWrite 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)