多次下载 - CSV 文件

Multiple download - CSV file

我在下面有一个脚本,它可以从 1 的特定行下载文件,仅 CSV 文件。我没问题,它运行良好,所有文件都下载到我的 'Python Project' 文件夹,root.

但我想在这里添加功能,首先,不仅要下载 1 个,还要下载多个(20 个或更多)CSV 文件,这样我就不必在这里手动更改名称了 - open(' name1.csv') 每次我的脚本完成工作。第二个请求,下载需要放在与下载来自的 csv 文件同名的文件夹中。希望我足够清楚:)

那么我可以:

任何帮助或建议将不胜感激:)非常感谢!

from collections import Counter
import urllib.request
import csv
import os

with open('name1.csv') as csvfile:  #need to add multiple .csv files here.
    reader = csv.DictReader(csvfile)
    title_counts = Counter()
    
    for row in reader:
        name, ext = os.path.splitext(row['link'])
        title = row['title']
        title_counts[title] += 1
        title_filename = f"{title}_{title_counts[title]}{ext}".replace('/', '-') #need to create a folder for each CSV file with the download inside.
        urllib.request.urlretrieve(row['link'], title_filename)

对于 1:只需遍历包含所需文件名称的列表。 可以使用“os.listdir(path)”检索列表,其中 returns 包含在您的“路径”(在您的案例中包含 csv 文件的文件夹)中的文件列表。

您需要添加一个外层循环来遍历特定文件夹中的文件。您可以将 os.listdir() which returns list of all entries or glob.iglob()*.csv 模式结合使用,以仅获取扩展名为 .csv 的文件。

您还可以对代码进行一些小的改进。您正在使用 Counter in the way that it can be replaced with defaultdict or even simple dict. Also urllib.request.urlretrieve() is a part of legacy interface which might get deprecated, so you can replace it with combination of urllib.request.urlopen() and shutil.copyfileobj().

最后,要创建一个文件夹,您可以使用 os.mkdir() but previously you need to check whether folder already exists using os.path.isdir(),它需要防止 FileExistsError 异常。

完整代码:

from os import mkdir
from os.path import join, splitext, isdir
from glob import iglob
from csv import DictReader
from collections import defaultdict
from urllib.request import urlopen
from shutil import copyfileobj

csv_folder = r"/some/path"
glob_pattern = "*.csv"
for file in iglob(join(csv_folder, glob_pattern)):
    with open(file) as csv_file:
        reader = DictReader(csv_file)
        save_folder, _ = splitext(file)
        if not isdir(save_folder):
            mkdir(save_folder)
        title_counter = defaultdict(int)
        for row in reader:
            url = row["link"]
            title = row["title"]
            title_counter[title] += 1
            _, ext = splitext(url)
            save_filename = join(save_folder, f"{title}_{title_counter[title]}{ext}")
            with urlopen(url) as req, open(save_filename, "wb") as save_file:
                copyfileobj(req, save_file)

你可以帮助我的国家,检查my profile info