简体   繁体   中英

Python FileNotFoundError: [Errno 2] No such file or directory:

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'

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 .... 

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:

with open(filename,'r') as f:替换 line with open(filename,'r') as f: with with open(os.path.abspath(filename),'r') as f:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM