
以上是檔案和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'
我做錯了什么?
uj5u.com熱心網友回復:
有一個名為“當前作業目錄”的 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 所在的位置。
有幾種方法可以繼續更改腳本以滿足您的需求:
- 您可以將 移動
private_key.pem到當前作業目錄 - 您可以讓您的腳本在 中查找
private_key.pem檔案Path(__file__).parent,這是您的腳本所在的目錄 - 您可以使用命令列引數來指定查找
private_key.pem. 我認為這是最好的路徑。您也可以將其與選項 1 結合使用,如果省略引數,則使用當前作業目錄作為默認目錄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/485463.html
上一篇:如何從檔案中獲取文本?
