Python,如何使嵌套循环适用于多列 csv 文件?

Python, How to make a nested loop works with multiple columns csv files?

我是 Python 的新手,我想使用来自多列 CSV 文件的数据来使函数工作,一行一行地在每个 运行.[=13 之间有一些延迟=]

这是我想要实现的:

  1. 读取范围内的第一个 CSV 文件(例如第 0 行到第 3 行)

  2. 使用一行的数据,放到函数里面的右边参数段,稍微延迟一下,下一行做同样的事情。

  3. 有些延迟,然后转到下一个 CSV 文件,直到最后一个 CSV 文件。

我试过以下代码,但没有用。以下代码适用于一列 CSV 文件。

我想用 CSV 文件中的数据填充 4 个参数, 使用相同的列 header 名称作为函数内的参数名称。

示例 csv 文件:

img_path,desc_1 title_1,link_1
site.com/image22.jpg,someTitle,description1,site1.com
site.com/image32.jpg,someTitle,description2,site2.com
site.com/image44.jpg,someTitle,description3,site3.com
from abc.zzz  import xyz
path_id_map = [
    {'path':'file1.csv', 'id': '12345678'},
    {'path':'file2.csv', 'id': '44556677'}
    {'path':'file3.csv', 'id': '33377799'}
    {'path':'file4.csv', 'id': '66221144'}]
s_id = None
for pair in path_id_map:
    with open(pair['path'], 'r') as f:
        for i in range(0, 3):      
            zzz.func1(img_path=f.readline().rstrip(','), title_1=f.readline().rstrip(','), 
            desc_1=f.readline().rstrip(','), link_1=f.readline().rstrip(','), B_id=pair['id'], 
            s_id=s_id)
            return zzz.func1(img_file=img_path, title_1=title_1, desc_1=desc_1, 
                 link_1=link_1, B_id=B_id, s_id=s_id)
            time.sleep(25) 

感谢您的帮助,让它发挥作用。

  • 每次调用 readline() 都会移到下一行。所以首先将该行保存到一个变量然后处理它。
  • rstrip only removes characters from the edges of the string. As you have no trailing commas, the use of rstrip in your code has no effect. It seems like you meant to use the split 方法取而代之的是采用逗号分隔的不同部分。
for pair in path_id_map:
    with open(pair['path'], 'r') as f:
        next(f)  # skip first header line
        for _ in range(0, 3):      
            line = next(f)
            img_path, desc_1, title_1, link_1 = map(str.strip, line.split(','))
            zzz.func1(img_path=img_path, title_1=title_1, desc_1=desc_1, 
                      link_1=link_1, B_id=pair['id'], s_id=s_id)

但是不需要手动解析csv文件。相反,您可以使用内置的 csv module, which has the DictReader that reads each line to a dict where the keys are the headers and the values are the value of each column with that header. This will allow you to simply unpack the row into the function call:

import csv

for pair in path_id_map:
    with open(pair['path'], 'r') as f:
        reader = csv.DictReader(f)
        for _ in range(0, 3):      
            line = next(reader)
            zzz.func1(B_id=pair['id'], s_id=s_id, **line)