我有一个以逗号分隔的用户及其权限列表,其中一些用户最多拥有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
知道为什么这不起作用?或者,有没有更好的方法来实现我想要的输出?也许正则表达式可以更好地工作?
答案 0 :(得分:1)
问题是这一行:
fields = 'USER','PERM1','PERM2','PERM3','PERM4',
'PERM5','PERM6','PERM7','PERM8'
您的代码正在执行fields = 'USER','PERM1','PERM2','PERM3','PERM4',
(记住元组和列表在最后一项之后可以有尾随逗号),然后创建另一个元组('PERM5','PERM6','PERM7','PERM8'
)并且不执行任何操作。
然后,当你创建csv.DictWriter
时,它只有第一个元组中的字段 - 因此你得到的错误。
解决方案很简单:在元组周围使用括号,然后为您提供隐含的行继续:
fields = ('USER','PERM1','PERM2','PERM3','PERM4',
'PERM5','PERM6','PERM7','PERM8')
您也可以使用反斜杠来转义换行符,但是括号可以更好地阅读。
答案 1 :(得分:0)
for perm in listOfPermissions:
user, perms = perm.split(',', 1)
for p in perms:
print "%s, %s" %(user, p)
将此内容写入文件:
with open('path/to/file', 'w') as outfile:
for perm in listOfPermissions:
user, perms = perm.split(',', 1)
for p in perms:
outfile.write("%s, %s\n" %(user, p))