-3

python unable to load files in same directory causing a lot of problems Running on MacOS 10.15.7, and using pycharm All my programs were running fine yesterday and now it can not seem to find these files.

with open('lorem.txt',mode='r') as file:
    for line in file:
        print(line)

this is returning this traceback

Traceback (most recent call last):
File "/Users/calblanco/PycharmProjects/pundont/main.py", line 2, in <module>
with open('lorem.txt','r') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'lorem.txt'

Both the python file and txt file are in the exact same directory. This is also happening in a few other programs I have that rely on reading files

martineau
  • 99,260
  • 22
  • 139
  • 249
jimdangle
  • 1
  • 1
  • 2
    That file does not exist in the current directory (which is not necessarily the same directory where the python script file is.) – John Gordon Feb 18 '21 at 00:29
  • 2
    The current directory may not be what you think it is if you're using PyCharm. Try printing out the value returned from calling `os.getcwd()`. – martineau Feb 18 '21 at 00:32
  • You can determine the directory the script is in and use it to determine the path to the data file (instead of counting on it being something). See [How do you properly determine the current script directory?](https://stackoverflow.com/questions/3718657/how-do-you-properly-determine-the-current-script-directory) – martineau Feb 18 '21 at 00:44

2 Answers2

2

Although the file is in the script directory, the program's current working directory may be somewhere else completely. This is especially the case with GUI programs like IDE's. When you run the program from the IDE there is likely a field for setting CWD in the run dialog.

But there is another way. When python runs a script, it includes it's file name in a variable called __file__. You can use that to locate the script's directory and from there build a path to any of its files. Using the pathlib module, you could do

from pathlib import Path

script_dir = Path(__file__).absolute().parent
lorem_file = script_dir/"lorem.txt"
with lorem_file.open() as file:
    for line in file:
        print(line, end="")
tdelaney
  • 55,698
  • 4
  • 59
  • 89
0

it maybe bash problem try to set file path like that

open('./lorem.txt','r')

or open terminal on the same file that this file exist