【问题标题】:Dict from JSON object not writing out to file using DictWriter来自 JSON 对象的字典未使用 DictWriter 写入文件
【发布时间】:2016-05-31 09:35:06
【问题描述】:

我正在使用 oauth2 库解析 jira 数据库,接收我正在使用 UTF-8 解码的字节对象,然后使用 json.loads 将结果字符串对象作为字典返回。然后我尝试使用DictWriter 将其写入平面文件,但它返回以下错误:

File "/Users/mharris/PycharmProjects/CodeRepo/jira_oauth.py", line 206, in <module>
    writer.writerows(data)
  File "/Users/mharris/anaconda/lib/python3.5/csv.py", line 156, in writerows
    return self.writer.writerows(map(self._dict_to_list, rowdicts))
  File "/Users/mharris/anaconda/lib/python3.5/csv.py", line 150, in <genexpr>
    return (rowdict.get(key, self.restval) for key in self.fieldnames)
AttributeError: 'str' object has no attribute 'get'

我正在做一个print(type(data)) 来验证它确实是一本字典。 这是我的代码的摘录:

with psycopg2.connect(
        host=settings.REDSHIFT_HOST,
        port=settings.REDSHIFT_PORT,
        database=settings.REDSHIFT_DATABASE,
        user=settings.REDSHIFT_USER,
        password=settings.REDSHIFT_PASS) as conn:

    cur = conn.cursor()

    get_cols = '''
    SELECT *
    FROM ods_jira.staging_jira_issues
    LIMIT 10
    '''

    cur.execute(get_cols)
    colnames = [desc[0] for desc in cur.description]

    max_res = 1000
    data_url = data_url_base + mk_data_endpoint(max_res, start_at)

with gzip.open('jira_data.txt.gz', 'w') as outf:
    writer = DictWriter(outf,
                        delimiter='|',
                        quotechar='"',
                        fieldnames=colnames,
                        extrasaction='ignore')

    for cycle in range(1):
        response, content = client.request(data_url, 'GET')
        if response['status'] != '200':
            raise Exception('Unable to access page, code was: ',
                            response['status'])

        str_resp = content.decode('utf-8')
        print(type(str_resp))
        data = json.loads(str_resp)
        print(type(data))
        writer.writerows(data)

        start_at += 1000

【问题讨论】:

    标签: python json csv python-3.x dictionary


    【解决方案1】:

    writerows 需要一个字典列表。如果您有一本字典,请使用 writerow。

    str_resp = content.decode('utf-8')
    print(type(str_resp))
    data = json.loads(str_resp)
    print(type(data))
    writer.writerow(data)
    

    【讨论】:

    • 新错误是:Traceback(最近一次调用最后一次):文件“/Users/mharris/PycharmProjects/CodeRepo/jira_oauth.py”,第 205 行,在 writer.writerow(data) 文件中“/Users/mharris/anaconda/lib/python3.5/csv.py”,第 153 行,在 writerow 返回 self.writer.writerow(self._dict_to_list(rowdict)) 文件“/Users/mharris/anaconda/lib/python3 .5/gzip.py",第 258 行,在 write data = memoryview(data) TypeError: memoryview: a bytes-like object is required, not 'str'
    • 所以看起来是因为我在用 gzip 做东西。
    • 试试 : with gzip.open('jira_data.txt.gz', 'wt')
    • 另外,您应该明确地将newline='' 传递给gzip.open(以及任何打开的文件以供csv 模块使用)以防止行结束翻译,让@987654325 @module 以独立于操作系统的方式正确处理它。
    猜你喜欢
    • 2011-03-13
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2016-08-18
    • 1970-01-01
    相关资源
    最近更新 更多