尝试读取与 python 文件位于同一目录中的文件但收到 FileNotFoundError

克里斯托弗·雅各布

在此处输入图像描述

以上是文件和python文件在同一目录下

文件是 private_key.pem

python文件是cloudfrontsignedcookie.py

cloudfrontsignedcookie.py文件中,我们有以下代码

 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)

但是我收到以下错误:

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'

我做错了什么?

瓦祖永利

有一个名为“当前工作目录”的 posix 属性,或者cwd,有时仅称为“工作目录”。当您运行脚本时,该脚本在您的上下文中运行cwd,而不是在脚本所在的路径中运行。在交互式 shell 中,cwd它由当前 shell 会话所在的目录定义,并且此属性由您在该交互式会话中运行的任何命令继承。脚本的位置不同。请参阅此代码:

#!/usr/bin/env python3

from pathlib import Path

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

当我运行它时,我看到了这个:

$ 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')

所以你可以看到,这cwd就是我当前的 shell 所在的位置。

有几种方法可以继续更改脚本以满足您的需求:

  1. 您可以将 移动private_key.pem到当前工作目录
  2. 您可以让您的脚本在 中查找private_key.pem文件Path(__file__).parent,这是您的脚本所在的目录
  3. 您可以使用命令行参数来指定查找private_key.pem. 我认为这是最好的路径。您也可以将其与选项 1 结合使用,如果省略参数,则使用当前工作目录作为默认目录。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章