![](/img/trans.png)
[英]python: FileNotFoundError: [Errno 2] No such file or directory
[英]Python FileNotFoundError: [Errno 2] No such file or directory:
我正在嘗試打開目錄中的所有“*.json”文件並從中獲取一些數據
import json
import os #os module imported here
import glob
path = 'C:\Saba\Python Workspace'
for filename in os.listdir(path):
if filename.endswith('.json'):
with open(filename,'r') as f:
data = json.load(filename)
print(data['key'],end="*")
for path in data['paths']:
print(path['method'],end="*")
for resources in path['resources']:
print(resources['key'],end="*")
print("\b"+"$")
這是我得到的錯誤:
Traceback (most recent call last):
File "c:/Saba/Python Workspace/folder.py", line 9, in <module>
with open(filename,'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'order-securityTransferOrders-service-v1.0.0-inventory.json'
您正在不同的路徑中運行腳本。 添加文件名的絕對路徑即可解決問題。
import os.path
for filename in os.listdir(path):
abs_file_path = os.path.abspath(filename)
if filename.endswith('.json'):
with open(abs_file_path,'r') as f:
# your code ....
你在哪里運行這個腳本? Python 嘗試在當前腳本文件夾中搜索您的 Json 文件。
如果你想讓 Python 在給定的路徑中找到,你應該像這樣寫:
with open(os.path.join(path,filename) ,'r') as f:
with open(filename,'r') as f:
替換 line with open(filename,'r') as f:
with with open(os.path.abspath(filename),'r') as f:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.