[英]Csv Reader expected a character buffer object
我有DNS記錄為csv格式,並且它具有主機名和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)
原因是您正在嘗試將元組寫入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])
這是非常快速編寫的代碼,但希望對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.