python - 具有多个值的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
错误在哪里?
解决方案
尝试在循环内初始化您的列表:
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
我希望这有帮助。
推荐阅读
- bash - 检查多个 Bash 变量是否为空/未设置并运行这个或那个
- object - 如何获取 COM 对象中可用的函数列表?
- mysql - 将mysql数据库迁移到oracle 9i
- c# - c#在一个exe中绑定可执行文件和参数
- python - Python Modbus字符串解码问题
- .net-core - 使用 AutoMapper ProjectTo 和 Moq.EntityFrameworkCore 进行单元测试
- javascript - 从多个对象数组中获取唯一值
- python - 转换用透明度保存的 TIFF 图像无法在 Python 中转换为 JPEG 图像
- r - 带有ggplot的多个堆叠条形图
- flutter - 颤振未处理的错误类型'_InternalLinkedHashMap
' 不是类型 'Map 的子类型 '