簡體   English   中英

python將輸出寫入csv文件

[英]python writing output to csv file

嗨,我正在嘗試放入方法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)


如果那是您需要的,只需添加

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']

您忘記了在函數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 這是預期的行為! 雖然在您初次學習時不是很直觀!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM