【问题标题】:AttributeError: 'str' object has no attribute 'read' when reading a JSON fileAttributeError:“str”对象在读取 JSON 文件时没有“read”属性
【发布时间】:2018-07-05 02:17:57
【问题描述】:

这是我想要实现的目标: 我正在尝试检查一个目录并列出其所有文件夹和文件。如果有一个文件夹,我想列出这个文件夹中的所有文件(它们都是 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()

【问题讨论】:

  • 该行代码不在发布的代码中...也请发布整个错误。
  • @AChampion,请看代码中的json_load=json.load(x.read())。此外,整个错误已发布。
  • 另外,请只发布与您遇到的实际问题相关的代码......大部分代码是无关紧要的
  • @RushabhMehta,完成!
  • 您尚未发布整个错误,您将有一个回溯,其中显示导致错误的行号和代码。 return loads(fp.read(),... 不在上面的代码中,因此推测错误包含其他详细信息。但是,您使用的是load(),因此您只需要传入x,例如json.load(x)。您发布的错误行暗示内部json.load(x) 只是调用json.loads(x.read()),所以您目前拥有的是json.loads(x.read().read()),这显然是错误的。

标签: json python-3.x


【解决方案1】:

感谢@AChampion。我的一个文件夹中有一些 txt 文件!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2021-06-03
    • 2019-07-30
    相关资源
    最近更新 更多