Reading file in python on the Mac

1k Views Asked by At

I am very new on this platform and I need help reading a file in python. First, it was a docx file because I am using Mac, I converted it into a txt file ,but still have file not found error.

Here is some code:

opdoc = open('PRACT.txt') print(opdoc.readline()) for each in opdoc : print(each)

and this the error output: FileNotFoundError: [Errno 2] No such file or directory: 'PRACT.txt'

2

There are 2 best solutions below

1
On

Unless your file is in the exact same directory as your python file, you'll get this error. Even then, it's best practice to include some sort of relative filepath, like "./PRACT.txt". In general, your issue stems from the fact that Python doesn't know where to look for your file, and where it does know to look, the file isn't there. You need to provide the full path to the file, like:

with open("path/to/file/PRACT.txt", "rb") as f:
    # read file etc
1
On

Make a new folder and put the txt file in it and also the programme itself. Or just put them in the same directory.

As you have this error ( No such file or directory: 'PRACT.txt') your code couldn't find the file because they were not in the same directory. When you use open("README.txt") the programme is assuming that the text is in the same directory as your code. If you don't want them in the same directory you could also try open(f"[file_path]") and that should work.