首页 > 解决方案 > 分别从具有不同名称的另一个文件中命名不同的文件

问题描述

我创建了一个脚本来下载多个图像。我有另一个文件(linkVars.py),其中有要下载的图像的 URL。此脚本导入linkVars.py文件,然后一次读取一个 URL,从 URL 下载该图像,并将其写入名为{file_name}.jpg的文件中

下面是解释上面行的代码:

import linksVars as lV # file with urls

def download_url(url):
    # Creating a function 
        print(f"\nDownloading from: ", url)
        file_name_start_pos = url.rfind("=") + 1 # naming image by using text in url
        name_from_url = url[file_name_start_pos:]
        file_name = name_from_url
    
        r = requests.get(url, stream=True)
        if r.status_code == requests.codes.ok:
       # Opening the image file to write data in it
                    with open(f'{file_name}.jpg', 'wb') as f:
                        for data in r:
                            f.write(data)

现在,我在name_file.txt(外部文件)中写入了多个名称。当我下载图像时,我想从name_file.txt 中的一个名称命名{ file_name }.jpg中的 file_name。然后当代码开始下载下一个文件时,name_file.txt中的下一个名称应该分配给{file_name}.jpg如果有人可以帮助我,我将不胜感激!

下面是完整的代码:

import requests
import linksVars as lV

def download_url(url):
    print(f"\nDownloading from: ", url)
    file_name_start_pos = url.rfind("=") + 1
    name_from_url = url[file_name_start_pos:]
    file_name = name_from_url

    r = requests.get(url, stream=True)
    if r.status_code == requests.codes.ok:
                with open(f'{file_name}.jpg', 'wb') as f:
                    for data in r:
                        f.write(data)

links = lV.List1
try:
    for listLinks in links:
        download_url(listLinks)
except(KeyboardInterrupt):
    print("\n\n===> Script ended by USER! <===")

标签: pythonfilenaming

解决方案


尝试这个:

import requests
import linksVars as lV # Importing file with URLs stored in variables
import nameVars as nV # Importing file with names stored in variables

links = lV.List1    # List1 is the list of URLs stored in variables
names = nV.Name1    # Name1 is the list of names stored in variables

# This function will download image from URL and name it from Name1
def download_url(url, names):
    print(f"\nDownloading from: ", url)
    file_name_start_pos = url.rfind("v=") + 1   # It will find "v=" in given URL and move to next line
    name_from_url = url[file_name_start_pos:]   
    file_name = names

    r = requests.get(url, stream=True)
    if r.status_code == requests.codes.ok:
        with open(f'{file_name}.jpg', 'wb') as f:   # Downloaded file will opened and named
            for data in r:
                f.write(data)

try:
    for listLinks, listNames in zip (links, names): # "For loop" will use two arguments
        download_url(listLinks, listNames)

except(KeyboardInterrupt):
    print("\n\n===> Script ended by USER! <===")

推荐阅读