【问题标题】:Csv Reader expected a character buffer objectCSV 阅读器需要一个字符缓冲区对象
【发布时间】:2016-02-26 07:59:11
【问题描述】:

我有 csv 格式的 DNS 记录,它有 HostName 和 IPAdress 标签。 它包括公共和私有(“192.168”、“172.16”和“10.0”)IP 地址,并且我想彼此分开。当我运行我的代码时,我采用了“预期的字符缓冲区对象”错误代码。如何解决这个问题

import csv
with open('Dns.csv', 'rb') as csvfile:
 reader = csv.DictReader(csvfile)
 for row in reader:
  if "10.205" in row['IPAddress']:
  file10=open("Zone10.txt","a")
  a=(row['hostname'], row['IPAddress'])
  file10.write(a)

【问题讨论】:

    标签: python dns record


    【解决方案1】:

    原因是您试图将元组写入file10。所以下一行应该修改

    a=(row['hostname'], row['IPAddress'])
    file10.write(a)
    

    例如,如果你要将它写成一个字符串,你可以这样做:

    file10.write(' '.join(a))  # it will work 
    

    a='{}{}'.format(row['hostname'], row['IPAddress'])
    file10.write(a)
    

    顺便说一句,最好使用上下文管理器打开file10

    关于 CSV 输出的评论:

    output = []
    for row in reader:
        if "10.205" in row['IPAddress']:
            output.append(row)
    if output:
        with open('Zone.csv', 'wb') as zonefile:
            writer = csv.DictWriter(zonefile, fieldnames=output[0].keys())
            writer.writeheader()
            writer.writerows([row for row in output])
    

    这是非常快速编写的代码,但我希望它会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2013-06-29
      • 2014-10-03
      • 2012-09-17
      • 2018-06-14
      相关资源
      最近更新 更多