将结果导出到CSV文件

时间:2018-10-12 18:32:23

标签: python python-3.x csv

我对编码还很陌生,但是我一直坚持这个问题。用python编写。

import logging
import os
import sys
import json
import pymysql
import requests
import csv

## set up logger to pass information to Cloudwatch ##
#logger = logging.getLogger()
#logger.setLevel(logging.INFO)

## define RDS variables ##
rds_host = 'host'
db_username = 'username'
db_password = 'password'
db_name = 'name'

## connect to rds database ##
try:
  conn = pymysql.connect(host=rds_host, user=db_username, password=db_password, db=db_name, port=1234,
                     connect_timeout=10)
except Exception as e:
  print("ERROR: Could not connect to MySql instance.")
  print(e)
  sys.exit()
print("SUCCESS: Connection to RDS mysql instance succeeded")


def main():
  with conn.cursor() as cur:
      cur.execute("SELECT Domain FROM domain_reg")
      domains = cur.fetchall()

  # logger.info(domains)

  conn.close()

 new_domains = []
 for x in domains:
      a = "http://" + x[0] + ("/orange/health")
      new_domains.append(a)



  print(new_domains)

  for y in new_domains:
      try:
          response = requests.get(y)
          if response.status_code == 200:
              print("Domain " + y + " exists")
          else:
              print("Domain " + y + " does not exist; Status code = " + str(response.status_code))
      except Exception as e:
          print("Exception: With domain " + y)

  with open("new_orangeZ.csv", "w", newline='') as csv_file:
      writer = csv.writer(csv_file, delimiter=',')
      for line in new_domains:
      writer.writerow([new_domains])

if __name__ == "__main__":
  main()

此代码确实创建了一个CSV文件,但是并没有完全导出我想要导出的文件。它只会创建一个仅列出“ Y”的csv文件,而我了解这是因为我在writer.writerow中调用了“ new_domains”。我试图弄清楚如何还将与if else语句匹配的打印功能导出到csv中。很抱歉,这听起来像是胡言乱语,就像我说的那样,我对编码非常陌生。希望发布一张我在csv文件中得到的图片以及我想要的图片,但是我对stackoverflow还是陌生的,所以它不允许我发布图片哈哈。

谢谢!

2 个答案:

答案 0 :(得分:1)

print()仅在屏幕上显示字符串。 您需要在某个地方记住它们,例如在新列表中:

result=[] #somewhere at the beginning
...
    print("Domain " + y + " exists")
    result.append([y,"Domain " + y + " exists"]) #after each print

,然后使用类似的方式将两者保存在CSV文件中:

    for domain,status in new_domains:
        writer.writerow([domain, status])

再次保存域更容易,因为for / in可能不会保持其顺序。

顺便说一句,用“ for new_domains中的行:”我想您应该已经在“ new_domains”的CSV记录中写了“ line” ...

答案 1 :(得分:0)

  

问题:我试图弄清楚如何还将与if else语句匹配的打印功能导出到csv

如果要print进入文件,则必须将文件对象赋予print(..., file=<my file object>。在您的示例中,将for ...移到with ...内。

  

注意:将csv.writer(...用于 csv数据不是一个好主意”

with open("test", "w", newline='') as my_file_object:
    for y in new_domains:

  

来自Python Documentation - Built-in Functions

     
    

打印(*对象,sep ='',结束='\ n',file = sys.stdout,flush = False)

         

objects打印到文本流file,并用sep分隔,后跟end
    sependfileflush(如果存在)必须作为关键字参数给出。

         

file参数必须是具有写入(字符串)方法的对象;如果不存在或无,则将使用 sys.stdout

  
相关问题