我想创建一种方法,在其中可以定义行头的CSV文件的结构(Excel的明显扩展名应遵循)。在这种方法中,定义的简单重新排序将移动输出中的列。
我的第一次尝试是使用namedtuple
。实际上满足了我的大部分需求,但是我无法创建一个空行来根据需要填充它。我尝试使用recordclass
,但是有很多相同的问题。
我的输出文件可能有> 30列,因此必须创建一堆None
的新实例变得非常草率。我还希望能够在结构中添加一列而不必更新__init__
等。
我的主意伪代码(使用namedtuple
进行说明)将是:
class TableRow(namedtuple(TableRow, "id name password hostip"))
__slots__ = ()
class TableRowHeader:
def __init__(self):
header = TableRow()
header.id = 'ID'
header.name = "Name"
header.password = "Password"
header.hostip = "Host IP"
class OutputTable():
def __init__(self):
self.header = TableRowHeader()
self.rows = list()
def add(self, new_row):
# Example assumes new_row is an instance of TableRow
self.rows.append(new_row)
def to_csv(self, file_name):
with open(file_name, 'w') as csv_file:
# creating a csv writer object
csv_writer = csv.writer(csv_file)
# writing the fields
csv_writer.writerow(self.header)
for row in sorted(self.rows):
csv_writer.writerow(row)
outtable = OutputTable()
row = TableRow()
row.id = 1
row.name = 'Matt'
row.hostip = '10.0.0.1'
row.password = 'obvious'
outtable.add(row)
outtable.to_csv('./example.csv')
我喜欢这种模式,但无法找到一种在Python中处理该问题的干净方法。
您想要这样的东西吗?
import csv
from collections import namedtuple
TableRowShort = namedtuple('TableRow', "id name password hostip")
TableRowFull = namedtuple('TableRowFull', "id name password hostip description source admin_name")
class TableRowOptional:
def __init__(self, id, name, password=None, hostip=None, description=None, source=None, admin_name=None):
super().__init__()
self.id = id
self.name = name
self.password = password
self.hostip = hostip
self.description = description
self.source = source
self.admin_name = admin_name
class OutputTable():
def __init__(self):
self.headers = []
self.rows = list()
def add(self, row):
if hasattr(row, '_asdict'):
value = row._asdict()
elif hasattr(row, '__dict__'):
value = row.__dict__
elif isinstance(row, dict):
value = row
else:
raise ValueError('Not supported row type: {}'.format(type(row)))
for header in value.keys():
if header not in self.headers:
self.headers.append(header)
self.rows.append(value)
def to_csv(self, file_name):
with open(file_name, 'w') as csv_file:
# creating a csv writer object
csv_writer = csv.writer(csv_file)
# writing the fields
csv_writer.writerow(self.headers)
for row in self.rows:
csv_writer.writerow([row.get(header, None) for header in self.headers])
outtable = OutputTable()
outtable.add(TableRowShort(1, 'Matt', 'obvious', '10.0.0.1'))
outtable.add(TableRowFull(2, 'Maria', 'obvious as usual', '10.1.0.1', 'some description', 'localnet', 'super_admin'))
outtable.add(TableRowOptional(3, 'Maria', hostip='10.1.0.1', description='some description', source='localnet'))
outtable.add({
'id': 1337,
'name': 'hacker',
'hostip': '127.0.0.1',
'extra': "I've hacked you guys lol!",
})
outtable.to_csv('./example.csv')
此解决方案为您提供了将一些“准备好的命名元组,普通对象(使用__dict__
接口)和原始dict对象作为行存储的界面。它根据提供的行结构自动管理CSV标头:]
看起来很清楚,对我有用。您怎么看?
输出CSV
# > cat example.csv
id,name,password,hostip,description,source,admin_name,extra
1,Matt,obvious,10.0.0.1,,,,
2,Maria,obvious as usual,10.1.0.1,some description,localnet,super_admin,
3,Maria,,10.1.0.1,some description,localnet,,
1337,hacker,,127.0.0.1,,,,I've hacked you guys lol!