

It is really important to keep track of which directory you are in so you can reference the correct path name. If you don't have the correct path for the file, then you will get an error message like this: open("random-text.txt") In order to access that file in the main.py, you have to include the folder name with the name of the file. In this example, the random-text file is inside a different folder then main.py: If your text file is in a different directory, then you will need to reference the correct path name for the text file.

Here is an example of both files being in the same directory: If the text file and your current file are in the same directory ("folder"), then you can just reference the file name in the open() function. This is the basic syntax for Python's open() function: open("name of file you want opened", "optional mode") File names and correct paths If you want to read a text file in Python, you first have to open it. In this article, I will go over the open() function, the read(), readline(), readlines(), close() methods, and the with keyword. In Python, there are a few ways you can read a text file.
