Python 在 Linux 的 Windows 子系统中找不到文件

Python can't find file in Windows Subsystem for Linux

我在 WSL 的 Ubuntu 环境中使用 python 编写了一个脚本。

我在Windows中下载了firebase的私钥"serviceAccountKey.json",然后将其移动到我在wsl中的工作目录。 (使用 'mv mnt/c/Users/Yiu/Downloads/serviceAccountKey.json ~/projects/scrape')。现在,我试图将该文件传递给 Certificate() 但我收到一个文件未找到错误。

我做了一些研究,发现权限可能存在一些问题,但文件都是读取、写入和执行权限。

脚本:

import requests
from bs4 import BeautifulSoup
import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.Certificate("~/projects/scrape/serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()

如何摆脱找不到文件的错误?

您需要设置绝对路径,因为 ~ 会因调用用户而异

cred = credentials.Certificate("~/projects/scrape/serviceAccountKey.json")

~ 通常由 shell 扩展为 $HOME 的值。这不适用于您的程序中的路径,包括 Python 程序,除非它们也进行类似的替换; Python 在 pathlib.Path.expanduser and os.path.expanduser 中为此提供实用程序。