首页 > 解决方案 > AttributeError:“str”对象在读取 JSON 文件时没有“read”属性

问题描述

这是我想要实现的目标:我正在尝试检查一个目录并列出其所有文件夹和文件。如果有一个文件夹,我想列出这个文件夹中的所有文件(它们都是 JSON 格式),然后,我想打开每个 JSON 文件并对它们执行一个功能。但是我收到以下错误,它似乎与 JSON 有关,有人可以告诉我我做错了什么吗?

return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'

这是我的代码:

import os
from os import listdir
import glob
import json
list_dir=[]
all_files=[]
read_file=[]

for r,d,f in os.walk(r'C:\aschemas-master'):  #show only directories along with path
   for dirs in d:
     filepath = os.path.join(r, dirs)
     list_dir.append(filepath)
for folders in list_dir:       
    all_files=os.listdir(folders)  
    for each_file in all_files:
        file_read=os.path.join(folders+'\\'+each_file)
        x=open(file_read)
        file_write=os.path.join(folders+'\\'+each_file+"_madh"+".txt")
        w=open(''.join(file_write),'w')
        **json_load=json.load(x.read())**
        for x in get_dotted_form("", json_load):  # calls the function
            w.write(x)
            w.write('\n')
        w.close()

标签: jsonpython-3.x

解决方案


功劳归于@AChampion。我的一个文件夹中有一些 txt 文件!


推荐阅读