【问题标题】:Writing to csv, 3 variables写入 csv,3 个变量
【发布时间】:2017-04-26 12:27:24
【问题描述】:

我正在尝试写入 .csv 文件 3 个变量:日期、最低、最高温度。我用数字代替了 tmax 和 tmin,因为我不想重复导入等。

这是我的代码:

import json
import datetime
import time
import csv
import sys

tmin = float(30.3333)
tmax = float(31.4444)

from datetime import datetime

i = datetime.now()
todayD = i.strftime('%Y/%m/%d')
minmax = [todayD, tmin, tmax]

with open("C:/Users/anderstn/Desktop/JsonToCsv/"+today+"_MinMax"+".csv", 'w', newline='') as e:
    dict_writer = csv.DictWriter(e, fieldnames=["Date", "Min Temp", "Max Temp"])
    dict_writer.writeheader()
    dict_writer.writerows(todayD, tmin, tmax)

我也尝试了几次迭代:

dict_writer.writerows(todayD: tmin: tmax)
dict_writer.writerows(todayD | tmin | tmax)
dict_writer.writerows(minmax)

通常错误如下:

Traceback (most recent call last):
  File "C:/Users/anderstn/Desktop/JsonToCsv/JsonImport.py", line 42, in <module>
    dict_writer.writerows(todayD, tmin, tmax)
TypeError: writerows() takes 2 positional arguments but 4 were given

干杯,

【问题讨论】:

  • 你试过像dict_writer.writerow(minmax)这样的writerow吗?
  • dict_writer.writerow() 适合您的情况。 data = {}data['date'] = todayDdata['min'] = tmindata['max'] = tmaxwriter.writerow(data)
  • 与上面 Sijan 相同的错误,我得到了 Azat:Traceback(最近一次调用最后):文件“C:/Users/anderstn/Desktop/JsonToCsv/JsonImport.py”,第 42 行,在 dict_writer.writerow(minmax) 文件“C:\Users\anderstn\AppData\Local\Programs\Python\Python36-32\lib\csv.py”,第 155 行,在 writerow 中返回 self.writer.writerow(self. _dict_to_list(rowdict)) 文件“C:\Users\anderstn\AppData\Local\Programs\Python\Python36-32\lib\csv.py”,第 148 行,在 _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError : 'list' 对象没有属性 'keys' 对于您的解决方案
  • 你需要发送一个我在上面修改过的字典结构。你试过吗?

标签: python csv


【解决方案1】:

首先你不需要将浮点数转换为浮点数,只需编写

tmin = 30.3333
tmax = 31.4444

DictWriter 与字典(dict 及其子类)一起使用,writerows 也与字典列表(或其他可迭代对象)一起使用,在我们的例子中 writerow 方法就足够了,所以我们需要将字典传递给writerow,而不是 list 实例。

最后你的样本可能看起来像这样

import csv

from datetime import datetime

tmin = 30.3333
tmax = 31.4444

i = datetime.now()
todayD = i.strftime('%Y/%m/%d')
minmax = [todayD, tmin, tmax]
fields_names = ["Date", "Min Temp", "Max Temp"]
# here we making dictionary from `minmax`
# because `DictWriter` works with dictionaries
data = dict(zip(fields_names, minmax))

# FIXME: here is the problem with name `today`, it is our `todayD` or something else?
with open("C:/Users/anderstn/Desktop/JsonToCsv/" + today + "_MinMax" + ".csv",
          'w', newline='') as e:
    dict_writer = csv.DictWriter(e,
                                 fieldnames=fields_names)
    dict_writer.writeheader()
    dict_writer.writerow(data)

【讨论】:

    【解决方案2】:

    writerows() 需要一个可迭代对象,每行包含一个对象。每一行都应该是一个列表。 writerow() 还需要一个可交互对象,每列包含一个对象。例如

    dict_writer.writerow([todayD,tmin,tmax])
    

    【讨论】:

    • Traceback(最近一次调用最后):文件“C:/Users/anderstn/Desktop/JsonToCsv/JsonImport.py”,第 42 行,在 dict_writer.writerow([todayD, tmin, tmax]) 文件“C:\Users\anderstn\AppData\Local\Programs\Python\Python36-32\lib\csv.py”,第 155 行,在 writerow 返回 self.writer.writerow(self._dict_to_list(rowdict))文件“C:\Users\anderstn\AppData\Local\Programs\Python\Python36-32\lib\csv.py”,第 148 行,在 _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'list' object没有属性“键”我收到此错误丹
    • 我的错误。您正在使用 DictWriter,因此您应该提供要写入的 dict 对象而不是列表。要么,要么只使用 csv.writer()
    【解决方案3】:

    DictWriter.writerows() 方法需要一个字典列表,因此您必须将 todayD、tmin、tmax 与创建 csv.DictWriter 时使用的键一起放入字典中,然后将此字典放入一个列表。

    另外,如果你只想写 todayD、tmin、tmax,你可以使用DictWriter.writerow() 来连续写一个单字典

    【讨论】:

      【解决方案4】:

      来自:– Sijan Bhandari

      todayD = i.strftime('%Y/%m/%d')
      minmax = {}
      minmax['Date'] = todayD
      minmax['Min Temp'] = tmin
      minmax['Max Temp'] = tmax
      
      
      
      with open("C:/Users/anderstn/Desktop/JsonToCsv/"+today+"_MinMax"+".csv", 'w', newline='') as e:
          dict_writer = csv.DictWriter(e, fieldnames=["Date", "Min Temp", "Max Temp"])
          dict_writer.writeheader()
          dict_writer.writerow(minmax)
      

      干杯,

      【讨论】:

        猜你喜欢
        • 2019-02-19
        • 2015-12-28
        • 1970-01-01
        • 1970-01-01
        • 2018-05-22
        • 2023-01-25
        • 1970-01-01
        • 2016-06-30
        • 1970-01-01
        相关资源
        最近更新 更多