Reputation: 31
I am trying to open all the '*.json' files in a directory and get some data out of them
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"+"$")
This is the Error i get :
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'
Upvotes: 2
Views: 18576
Reputation: 1
Where do you run this script ? Python tries to search for your Json file in the current script folder.
If you want Python to find within the given path, you should write somthin like :
with open(os.path.join(path,filename) ,'r') as f:
Upvotes: 0
Reputation: 1
replace line with open(filename,'r') as f:
with with open(os.path.abspath(filename),'r') as f:
Upvotes: 0
Reputation: 16436
You are running the script in different path. Adding the absolute path of the filename will do the trick.
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 ....
Upvotes: 1