从 CSV 文件迭代运行 Python 脚本

问题描述 投票:0回答:1

我正在尝试调整 Python 脚本,以便它可以针对包含值列表(即参数)的 CSV 文件运行。 CSV 文件中的每一行都需要再次运行脚本。

这是我的简单脚本“myscript.py”:

#! /usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('url', help='input URL')

args = parser.parse_args()

print('This is the argument')
print(args.url)

我和它一起跑步

python3 myscript.py https://www.bbc.co.uk

它输出:

This is the argument
https://www.bbc.co.uk

现在,如果我有一个 CSV 文件“urls.csv”,我希望能够运行:

python3 myscript.py urls.csv

这样脚本就可以从 url 列表中运行必要的次数来生成:

This is the argument
https://www.bbc.co.uk
This is the argument
https://www.itv.com
This is the argument
https://www.channel4.com
This is the argument
https://www.channel5.com

我可以使用 argparse 指令的某些变体来实现此目的,还是需要另一个脚本作为某种包装器?

python csv
1个回答
0
投票

如果您不需要传递 URL 作为参数,您可以像这样修改脚本:

#!/usr/bin/env python3

import csv
import sys

# Check if a CSV file was actually provided in the arguments
if len(sys.argv) != 2:
    print("Usage: python3 myscript.py <urls.csv>")
    sys.exit(1)

csv_file = sys.argv[1]

with open(csv_file, 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        if row:  # Checks if the row is not empty
            print('This is the argument')
            print(row[0])

此代码从指定的 CSV 文件中读取 URL 并一一打印它们。你可以像这样运行它:

python3 myscript.py urls.csv

© www.soinside.com 2019 - 2024. All rights reserved.