Python 无法将列表写回CSV

Python 无法将列表写回CSV,python,csv,Python,Csv,我试图编写一个代码,接收csv,对第一列中的值运行ping,然后将状态输出到第二列。代码中的所有内容都可以正常运行,直到它尝试写入csv时,我收到此错误 writer.writerows(列)中的第35行 TypeError:“str”不支持缓冲区接口 import os import csv from collections import defaultdict i = 0 #read file columns = defaultdict(list) with open('hosts.csv

我试图编写一个代码,接收csv,对第一列中的值运行ping,然后将状态输出到第二列。代码中的所有内容都可以正常运行,直到它尝试写入csv时,我收到此错误
writer.writerows(列)中的第35行 TypeError:“str”不支持缓冲区接口

import os
import csv
from collections import defaultdict
i = 0
#read file
columns = defaultdict(list)

with open('hosts.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        for (k,v) in row.items():
            columns[k].append(v)
f.close()
print('[DEBUG]', columns['host'])
print('[DEBUG] 1st host is', (columns['host'])[0])
print('[DEBUG]', columns['status'])

#ping hosts
hostname = (columns['host'])[i]
response = os.system("ping -n 1 " + hostname)
print ("[DEBUG]", response)
if response == 0:
    print (hostname, 'is up')
    (columns['status'])[i] = 'Up'
    i = i+1
else:
    print (hostname, 'is down')
    (columns['status'])[i] = 'Down'
    i = i+1

#write results
with open("hosts.csv", "wb") as f:
    writer =csv.writer(f)
    print("[DEBUG] just before write rows")
    writer.writerows(columns)
    print("[DEBUG] after write rows")
f.close()
csv包含以下内容

host,status,name
8.8.8.8,down,google.com
而且应该回来

host,status,name
8.8.8.8,Up,google.com

我使用的是Python3.4

您正在以一种格式读取CSV,并以另一种格式写入,其中的列是defaultdict,其中包含一个dict中的值列表

以下是解决此问题的更好方法,即维护原始文件结构:

import os
import csv

with open('hosts.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

hosts = [row['host'] for row in rows]
statuses = [row['status'] for row in rows]

print('[DEBUG]', hosts)
print('[DEBUG] 1st host is', hosts[0])
print('[DEBUG]', statuses)

for row in rows:
    #ping hosts
    hostname = row['host']
    response = os.system("ping -n 1 " + hostname)
    print ("[DEBUG]", response)
    if response == 0:
        print (hostname, 'is up')
        row['status'] = 'Up'
    else:
        print (hostname, 'is down')
        row['status'] = 'Down'

#write results
with open("hosts.csv", "wb") as f:
    writer = csv.DictWriter(f, reader.fieldnames)
    # to maintain the same structure from the original file, rewrite header in original position
    writer.writeheader()
    print("[DEBUG] just before write rows")
    writer.writerows(rows)
    print("[DEBUG] after write rows")
在实例化csv.DictWriter之前,您可以更改要在新文件中的字段名:

newfieldnames = csvreader.fieldnames
lastfield = newfieldnames.pop() # remove last field
if 'field_name' in newfieldnames:
    newfieldnames.remove('field_name') # remove by field name
writer = csv.DictWriter(f, newfieldnames)

是否有一种修改的方法,允许我在结尾处写文章时删除最后一列?用此信息更新了答案。