简体   繁体   English

如何遍历不同的 csv 文件的列表?

[英]How do I iterate a list over different csv files?

I am trying to create 3 new csv files (one for each element in itemTypes) and place the out in each file.我正在尝试创建 3 个新的 csv 文件(itemTypes 中的每个元素一个)并将输出放在每个文件中。 This is the code I have so far and I'm stuck:这是我到目前为止的代码,我被困住了:

itemTypes = ['phone','tower','laptop']
x = range(len(itemTypes)) 
for y in x:
    with open('test' + str(y) + '.csv', 'w+', newline='') as file4:
        test_writer = csv.writer(file4, delimiter=',')
        for row, entry in inventory.items():
            entry.insert(0, row)
            for line in entry:
                if itemTypes[y] in line:
                    del entry[2]
                    print(entry)
                    test_writer.writerow(entry)

I am looking for a way to open and write in x amount of files depending on how many items the user puts in itemTypes.我正在寻找一种方法来打开和写入 x 个文件,具体取决于用户在 itemTypes 中放入的项目数量。 In this case, it's 3 but I want to allow it to fit any number.在这种情况下,它是 3,但我想让它适合任何数字。 The output I have is only correct for test0.csv .我拥有的 output 仅适用于test0.csv But test1.csv and test2.csv have jumbled entries and I can't tell why.但是test1.csvtest2.csv条目混乱,我不知道为什么。

The desired output is that each item should have its own file, and in the file it each column should have the item ID, manufacturer name, price, service date, and list if it is damaged, order by ID.想要的 output 是每个项目都应该有自己的文件,并且在文件中每一列都应该有项目 ID,制造商名称,价格,服务日期,以及如果损坏的列表,按 ID 订购。

You need something like this:你需要这样的东西:

itemTypes = ['phone','tower','laptop']
for item_type in itemTypes:
    with open(f'{item_type}.csv', 'w+', newline='') as file4:
        test_writer = csv.writer(file4, delimiter=',')
        for row, entry in inventory.items():
            entry.insert(0, row)
            for line in entry:
                if itemTypes[0] in line:
                    del entry[2]
                    print(entry)
                    test_writer.writerow(entry)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM