![](/img/trans.png)
[英]Python/Jupyter getting a FileNotFoundError when attempting to read an excel file however said file is in the correct directory
[英]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 所在的位置。
有幾種方法可以繼續更改腳本以滿足您的需求:
private_key.pem
移動到當前工作目錄Path(__file__).parent
中查找private_key.pem
文件,這是您的腳本所在的目錄private_key.pem
的目錄。 我認為這是最好的路徑。 您也可以將其與選項 1 結合使用,如果省略參數,則使用當前工作目錄作為默認目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.