0

When I use no path for ex.

filename = 'cats.txt'

with open(filename) as f:
    contents = f.read()

print(contents)

When I execute this code I receive a filenotfound error even though this file is in the same location as the currently running Python file. The only way this works is if I use an absolute path, which is really annoying when I'm working with a sizable list of filenames.

Anyone know the reason why this is happening? I also receive a similar error when writing to a brand new file, it doesn't save into the location of my currently running python file, but to my user location on PC and not any folder further. Very weird.

  • It is not weird. The python script directory is not the same as the "working directory". Use absolute paths, or change the working directory (https://www.tutorialspoint.com/python/os_chdir.htm), or in linux simply execute python from that folder, on windows I have no idea how can you do that since I hate windows... – simre May 14 '22 at 23:09
  • Are you using Pycharm? If yes you have to add working directory in Pycharm confuiguration where you setup python script path. – huzzzus May 14 '22 at 23:10

0 Answers0