Opening and reading files are actually one of the easiest things to learn in Python. You need to learn 3 key things:

  1. opening the file
  2. reading from the file & closing the file
  3. processing the file data

1. Opening the file

We need to use the Python command open() to open a file, and the open() command takes 2 arguments.

  1. The name of the file to open
  2. The mode to open the file. (I’ll talk more about this in a sec)

SO, when we open a file, we also need to store the command to open in a variable.

Untitled

2. Reading from the file

Now that we have the command to open the file saved under the variable file we can use dot notation to read the contents of the file with the function .readlines(). We save the read contents of the file in another variable. See below.

data = file.readlines()

Lastly, we need to close the file.

file.close()

Example

https://replit.com/@bitFez/reading-from-files-1#main.py

https://youtube.com/shorts/Lp8Why57s7A?si=qpJvpzpV3dNKqWfj