簡體   English   中英

嘗試讀取與 python 文件位於同一目錄中的文件但收到 FileNotFoundError

[英]attempting to read file in same directory as python file but getting 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'

我做錯了什么?

有一個名為“當前工作目錄”或cwd的 posix 屬性,有時簡稱為“工作目錄”。 當您運行腳本時,該腳本在您的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. 您可以讓腳本在Path(__file__).parent中查找private_key.pem文件,這是您的腳本所在的目錄
  3. 您可以使用命令行參數來指定查找private_key.pem的目錄。 我認為這是最好的路徑。 您也可以將其與選項 1 結合使用,如果省略參數,則使用當前工作目錄作為默認目錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM