Python FileNotFoundError:[错误2]没有此类文件或目录 [英] Python FileNotFoundError: [Errno 2] No such file or directory

查看:474
本文介绍了Python FileNotFoundError:[错误2]没有此类文件或目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自脚本的以下代码段

I have the following snippet from a script

credentials = ServiceAccountCredentials.from_json_keyfile_name('tok.json', ['https://www.googleapis.com/auth/analytics.readonly'])

这是用于Google Analytics(分析)中的身份验证 但是,当我在自己的网站上运行脚本时,日志报告以下错误:

This is for auth in google analytics But when I run the script on my site, the logs report the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'tok.json'

我尝试将tok.json放到服务器上我能想到的所有位置(目录?),但错误不会消失

I tried putting tok.json in all places (directories?) I can think of on the server, but the error does not disappear

推荐答案

我也遇到了同样的错误.我发现,如果我在运行程序之前进入该目录,它将运行良好.但是显然,这不是您每次都要手动执行的操作.因此,我调整了file.json以包括文件的绝对路径.换句话说:

I had this same error. I found out that if I cd into the directory before running the program it runs fine. But obviously, that's not something you'd want to manually do every time. So, I adjusted the file.json to include the absolute path to the file. In other words:

代替:

'tok.json'

我将其更改为:

'user/folder/tok.json'

我不确定这是否是最好的解决方法,因为如果您将文件移动到新目录中,它会中断,但是它对我有用.

I'm not sure if this is the best way to go about it since it will break if you ever move the files to a new directory, but it worked for me.

我认为问题在于,程序运行时正在查找终端/服务器当前所在的任何文件夹,而不必在程序的文件夹中.因此,您必须明确告诉它要去哪里.

I think the problem is that when the program runs it's looking in whatever folder the terminal/server is currently in, not necessarily in the program's folder. So you have to explicitly tell it where to go.

这篇关于Python FileNotFoundError:[错误2]没有此类文件或目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆