You have seen various types of data holders before: integers, strings, lists. But so far, we have not discussed how to read or write files.
Complete Python Bootcamp: Go from zero to hero in Python 3
You can read a file with the code below.
The file needs to be in the same directory as your program, if it is not you need to specify a path.
The first part of the code will read the file content. All of the lines read will be stored in the variable content. The second part will iterate over every line in the variable contents.
If you do not want to read the newline characters ‘\n’, you can change the statement f.readlines() to this:
content = f.read().splitlines()
Resulting in this code:
While the codes above work, we should always test if the file we want to open exists. We will test first if the file does not exist, if it does it will read the file else return an error. As in the code below: