首页 > 解决方案 > 具有多个值的csv上的Python for循环

问题描述

我有一系列 csv,我想读取一些唯一值,然后打印每个 csv 的每个值。为了更好地解释它:我有几个带有 Type 和 Publisher 列的 csv。在每个 csv 中,Type 和 Publisher 列可能具有重复多次的相同值。如果在类型栏中有,即“文件”“文件”“记录”“文件”“记录”,我只想打印“文件”和“记录”。

我正在尝试:

publisher = [] #create lists for each value we want
type = []
for rec in attachment: #attachment is a list with the url of csv
    newFile = rec.replace("\\","/")
    print("I'm searching in "+newFile)
    download = requests.get(newFile) #get the file from url
    decoded_content = download.content.decode('utf-8') #decode in utf-8

    csvFile = csv.DictReader(decoded_content.splitlines(), delimiter='\t')  
    csvFile.fieldnames = [field.strip().lower() for field in csvFile.fieldnames]
        for row in csvFile:
          publisher.append(row["publisher"])
          type.append(row["type"])
    print(";".join(set(self.type)))
    print(";".join(set(self.publisher)))

这只是将不同 csv 的所有值打印在一起,只要它搜索到下一个 csv。

所需的输出将是:

I'm searching in File 1
record; file
Publisher1
I'm searching in File 2
file
Publisher 2; Publisher 2A

错误在哪里?

标签: pythonpython-3.xcsv

解决方案


尝试在循环内初始化您的列表:

for rec in attachment: #attachment is a list with the url of csv
    publisher = []                      # <-- HERE
    type = []                           # <-- HERE
    newFile = rec.replace("\\","/")

而不是列表,您可以使用集合开始:

for rec in attachment: #attachment is a list with the url of csv
    publisher = set()
    type = set()
    newFile = rec.replace("\\","/")

如果你使用集合,你会使用add而不是append

我希望这有帮助。


推荐阅读