Home > Software design >  attempting to read file in same directory as python file but getting FileNotFoundError
attempting to read file in same directory as python file but getting FileNotFoundError

Time:05-31

enter image description here

The above is the file and the python file in the same directory

the file being private_key.pem

the python file being cloudfrontsignedcookie.py

within the cloudfrontsignedcookie.py file we have the following code

 print('its about to happen yo.........................')
 with open('private_key.pem', 'r') as file_handle:
      private_key_string = file_handle.read()
      print('here is the stuff')
      print(private_key_string)

however I get the following error:

File "/Users/bullshit/Documents/softwareprojects/shofi/backend/virtualshofi/backend/cloudfrontsignedcookie/cloudfrontsignedcookie.py", line 28, in generate_signed_cookies
    return dist.create_signed_cookies(resource,expire_minutes=expire_minutes)
  File "/Users/bullshit/Documents/softwareprojects/shofi/backend/virtualshofi/backend/cloudfrontsignedcookie/cloudfrontsignedcookie.py", line 89, in create_signed_cookies
    with open('private_key.pem', 'r') as file_handle:
FileNotFoundError: [Errno 2] No such file or directory: 'private_key.pem'

what is it that I am doing wrong?

CodePudding user response:

There is a posix property called the "Current Working Directory", or cwd, sometimes referred to as just "Working Directory". When you run a script, that script runs within the context of your cwd, not the path where the script is located. In an interactive shell, the cwd is defined by the directory your shell is in. The location of the script is different. See this code:

#!/usr/bin/env python3

from pathlib import Path

print(f'{Path.cwd()=}')
print(f'{Path(__file__).parent=}')

When I run that, I see this:

$ pwd  # print working directory
/tmp
$ /Users/danielh/temp/2022-05-30/path-problem.py
Path.cwd()=PosixPath('/private/tmp')
Path(__file__).parent=PosixPath('/Users/danielh/temp/2022-05-30')

So you can see, the cwd is where my current shell is.

There are a couple ways to proceed with changing your script to suit your needs:

  1. You can move the private_key.pem to your current working directory
  2. You can have your script look for the private_key.pem file in Path(__file__).parent, which is the directory your script is located in
  3. You can take a command line argument that specifies the directory where to look for the private_key.pem. I think this is the best path. You can also combine this with with option 1, using your current working directory as a default if the argument is omitted.
  • Related