简体   繁体   English

重命名和下载链接 - CSV 文件

[英]Rename and download links - CSV file

I have a CSV file with 6 columns and many rows.我有一个 CSV 文件,其中包含 6 列和许多行。 I would like to download all the png or jpg from the column 'link' in a folder with the same name of my CSV file.Then I would like to rename these images with each 'title' content.我想从与我的 CSV 文件同名的文件夹中的“链接”列下载所有 png 或 jpg。然后我想用每个“标题”内容重命名这些图像。

url1.png by name1.png for each files and until the last row.. url1.png by name1.png 每个文件,直到最后一行..

I started something with this -我以此开始了一些事情-

import csv
with open('name.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for row in reader:
        fileurl = row[0]
        filename = row[1]
        urllib.request.urlretrieve(fileurl, "name" + filename)

Rows example -行示例 -

在此处输入图像描述

Still learning.. Any help or suggestions to do this?还在学习.. 有什么帮助或建议吗?

Many thanks.非常感谢。

If I understand you correctly, you would like to download the file in the link column using the title column to form the filename.如果我没理解错的话,您想下载link栏中的文件,使用title栏来形成文件名。

This can be done as follows:这可以按如下方式完成:

import urllib.request
import csv
import os

with open('name.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    
    for row in reader:
        name, ext = os.path.splitext(row['link'])
        title_filename = f"{row['title']}{ext}".replace('/', '-')
        urllib.request.urlretrieve(row['link'], title_filename)

You can use .os.path.splitext() to split out the extension of the filename.您可以使用.os.path.splitext()来拆分文件名的扩展名。 This can then be used to combine with the entry from title to form a new filename.然后可以使用它与title中的条目组合以形成新的文件名。

For example:例如:

https://url.com/folder/url1.png would save as name1.png https://url.com/folder/url1.png将另存为name1.png


To deal with multiple identical title entries, you could investigate Python's Counter() to keep track of how many of each title you have.要处理多个相同的title条目,您可以研究 Python 的Counter()来跟踪您拥有的每个标题的数量。 For example:例如:

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

with open('name.csv') as csvfile:
    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}"
        urllib.request.urlretrieve(row['link'], title_filename)

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

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