python将输出写入csv文件

时间:2019-03-24 05:57:49

标签: python

嗨,我正在尝试将方法check()调用并写入CSV文件的消息放入,但是这是一个错误消息,提示“可预期,而不是NoneType”,不确定我的方法是否合乎逻辑,有人在这里帮我吗?


import json
import datetime
import time
import csv

t=45
h=50
d = datetime.datetime.now()
e = d.strftime("%Y-%m-%d %H:%M:%S")

def check():

 # check the temperatur and humidy in range or not
 with open('config.json') as myfile:

  data=json.load(myfile)

  if data["min_temperature"] <= t <= data["max_temperature"] and data["min_humidity"] <= h <= ["max_humidity"]:
   print(e,"OK")

  elif data["min_temperature"] > t or t > data["max_temperature"] : 
    print (e," BAD   Temperature is detected out of config range.")

  elif data["min_humidity"] > h or h > ["max_humidity"]:
     print (e,"BAD   Humidity is deteced out of range.") 
  else :
     print("Error")


result=check()

with open('report.csv', 'wb') as myfile2:
    wr = csv.writer(myfile2, quoting=csv.QUOTE_ALL)
    wr.writerow(result)


2 个答案:

答案 0 :(得分:1)

如果这是您所需要的,只需添加

def check():

# check the temperatur and humidy in range or not
    with open('config.json') as myfile:

    data=json.load(myfile)

    if data["min_temperature"] <= t <= data["max_temperature"] and data["min_humidity"] <= h <= ["max_humidity"]:
        return ','.join([e,"OK"])

    elif data["min_temperature"] > t or t > data["max_temperature"] : 
        return ','.join([e," BAD   Temperature is detected out of config range."])

    elif data["min_humidity"] > h or h > ["max_humidity"]:
        return ','.join([e,"BAD   Humidity is deteced out of range."]) 
    else :
        return "Error" //or Print Error depending on what you want

此外,您想以附加模式“ a”而不是“ wb”打开文件

将其更改为

with open('report.csv', 'a') as myfile2:
     myfile2.write(result+'\n')

或保持部分代码相同。只需将所有return语句转换为这种格式

return [e,'msg']

答案 1 :(得分:0)

您忘记在函数check中返回任何内容。这是一个人为设计的示例,可能会让您更容易了解发生了什么。

>>> def say_hello(name):
        print('Hello {}!'.format(name))
>>> say_hello('John Doe')
Hello John Doe!
>>> greeting = say_hello('John Doe')
Hello John Doe!
>>> greeting

>>> greeting is None
True

在Python中,如果函数没有返回值,则默认为None。这是预期的行为!初学时,这不是很直观!