我有一个以逗号分隔的用户及其权限的列表,其中一些用户最多有 8 个权限:
user_a, permission_1
user_b, permission_1, permission_2
user_c, permission_1, permission_2, permission_3
我需要我的输出是逗号分隔的用户和权限列表,其中每个用户和权限对都在单独的行上:
user_a, permission_1
user_b, permission_1
user_b, permission_2
user_c, permission_1
user_c, permission_2
user_c, permission_3
我下面使用 csv 模块的 python 代码目前不工作:
import csv
with open('user_list.csv') as user_list:
dict_reader = csv.DictReader(user_list)
ul = []
for row in dict_reader:
ul.append(row)
with open('output.txt','w') as output:
fields = 'USER','PERM1','PERM2','PERM3','PERM4',
'PERM5','PERM6','PERM7','PERM8'
dict_writer = csv.DictWriter(output, fields)
csv.DictWriter.writeheader(dict_writer)
for i in ul:
dict_writer.writerow(i)
它给了我以下追溯:
Traceback (most recent call last):
File "cops_ul_parse.py", line 15, in <module>
dict_writer.writerow(i)
File "C:\Python27\lib\csv.py", line 148, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\Python27\lib\csv.py", line 144, in _dict_to_list
", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: PERM8, PERM7, PERM6, PERM5
知道为什么这不起作用吗?或者,有没有更好的方法来完成我想要的输出?也许正则表达式会更好用?