将列表写入csv,并在迭代中添加新行,不重复



我无法向CSV写入列表的主要问题,我得到了这样的结果-https://i.stack.imgur.com/iXT06.png它给我看了很多专栏。我只需要一列,我不想要任何重复的。我该怎么办?

import csv
matched_dynamic_pattern = []
matched_static_pattern = []
not_matched = []
with open('processes.csv', 'r') as t1, open('static_patterns.csv', 'r') as t2:
commands = set()
reader = csv.DictReader(t1, dialect='excel', delimiter=',')
for row in reader:
commands.add(row['Command Line'])
static_patterns = set(t2.read().splitlines())

with open('results1.csv', 'w', newline='') as outFile:
writer = csv.writer(outFile)
for command in commands:
if command.startswith('"C:Program Files (x86)GoogleChromeApplicationchrome.exe" --type') or command.startswith('"C:\Users\test\AppData\Local\Microsoft\Teams\current\Teams.exe" --type'):
matched_dynamic_pattern.append(command)
else:
if command not in static_patterns:
not_matched.append(command)
writer.writerows([not_matched]) # THE PROBLEM LINE OF CODE
if command in static_patterns:
matched_static_pattern.append(command)

all_processes = len(commands)
exclude_dynamic = len(matched_dynamic_pattern)
exclude_static = len(matched_static_pattern)
print(all_processes - exclude_dynamic - exclude_static)
print('Results —', len(not_matched))
print(type(not_matched))

UPD:我找到了一个新的解决方案:

with open('results1.csv', 'w', newline='') as outFile:
for r in not_matched:
outFile.write(r + "n")
outFile.close()

但问题是:https://i.stack.imgur.com/wor77.png

您的代码在not_matched列表中累积不匹配的命令。但是,每次识别出不匹配的命令时,该列表的全部内容都会转储到CSV文件中。修复替换:

writer.writerows([not_matched]) # THE PROBLEM LINE OF CODE

带有

writer.writerow([command])      # N.B. writerow, not writerows

或者,在for循环终止后,将not_matched列表一次性写入CSV文件:

with open('results1.csv', 'w', newline='') as outFile:
writer = csv.writer(outFile)
for command in commands:
if command.startswith('"C:Program Files (x86)GoogleChromeApplicationchrome.exe" --type') or command.startswith('"C:\Users\test\AppData\Local\Microsoft\Teams\current\Teams.exe" --type'):
matched_dynamic_pattern.append(command)
else:
if command not in static_patterns:
not_matched.append([command])
else:
matched_static_pattern.append(command)
writer.writerows([not_matched])    # write all non-matched commands in one go 

还要注意,if command in static_patterns:可以简单地替换为else:

这个解决方案适合我!

with open('results1.csv', 'w', newline='') as outFile:
writer = csv.writer(outFile)
rows = zip(not_matched)
for row in rows:
writer.writerow(row)
outFile.close()

相关内容

  • 没有找到相关文章

最新更新