![](/img/trans.png)
[英]Error: FileNotFoundError: [Errno 2] No such file or directory:
[英]FileNotFoundError: [Errno 2] No such file or directory: error
我正在遍歷許多文件夾,使用以下代碼來獲取每個文件夾中的任何JSON文件:
def get_all_jobs():
for root_dir, _, file_names in os.walk(r'path'):
for file_name in file_names:
if file_name.endswith('.json'):
all_files = (f'{root_dir}/{file_name}')
for file in all_files:
with open(file_name, 'r', encoding="utf8") as json_file:
read_content = json.loads(json_file.read())
我得到這個錯誤:
FileNotFoundError: [Errno 2] No such file or directory:
並且沒有一個路徑可提供給一個文件夾,但是我有許多包含文件的文件夾。 我該如何解決?
在此處找到有關glob的信息。 glob將轉義所有內部目錄並遞歸匹配我們的模式。
def get_all_jobs():
for json_file in glob.iglob(path+"/**/*.json".replace('/',os.path.sep),recursive=True):
with open(json_file, 'r', encoding="utf8") as jf:
read_content = json.loads(jf.read())
Note:
這里path
是您有多個包含json文件的文件夾的基本目錄。
說明:
這里, glob
轉到您的基本目錄path
,從那里遞歸地轉到所有子文件夾,並檢查是否有文件包含.json擴展名,如果有,則給出該文件的完整路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.