Python FileNotFoundError:[错误2]没有这样的文件或目录:

时间:2019-06-26 05:26:19

标签: python

我正在尝试打开目录中的所有'* .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'

3 个答案:

答案 0 :(得分:0)

您正在其他路径中运行脚本。添加文件名的绝对路径即可解决问题。

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

答案 1 :(得分:0)

您在哪里运行此脚本? Python尝试在当前脚本文件夹中搜索您的Json文件。

如果您希望Python在给定的路径内找到,则应编写somthin,如:

<p>TimeStamp: <span id="demo"></span></p>
<script>
// Get the audio element with id="my_video_1"
var aud = document.getElementById("my_video_1");

// Assign an ontimeupdate event to the audio element, and execute a function if the current playback position has changed
aud.ontimeupdate = function() {myFunction()};

function myFunction() {
  // Display the current position of the audio in a p element with id="demo"
  document.getElementById("demo").innerHTML = aud.currentTime;
}
</script>

答案 2 :(得分:0)

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