首页 > 解决方案 > 下载后在python中重命名文件

问题描述

因此,我在 python 中编写了一个脚本来从 ftp 服务器下载文件。该脚本每小时使用 Windows 自动任务系统下载文件。我想知道是否可以在下载后重命名这些文件,以及是否有人可以建议我如何做到这一点。这是我当前的代码:

import shutil
import urllib.request as request
from contextlib import closing

def download(filename):
    with closing(request.urlopen("ftp://BUZZ:NotMyPassword@ftp.usaradio.com/"+filename)) as r:
        with open('C:/MyPath/usanews/'+filename,'wb') as f:
            shutil.copyfileobj(r, f)

files = ["newsbreak128.mp3", "toh35.mp3"]
for file in files:
    download(file)

标签: python

解决方案


在不过多更改函数的情况下执行此操作的方法是将要下载的文件名的值以及要以字典格式或作为列表中的元组重命名文件的名称传递。我将举一个后者的例子。如果您传递每对名称(要下载的名称及其新名称),然后通过索引指定您要尝试获取的名称,那么您的函数应该可以工作。

def download(filename):
    with closing(request.urlopen("ftp://BUZZ:NotMyPassword@ftp.usaradio.com/"+filename[0])) as r:
        with open('C:/MyPath/usanews/'+filename[1],'wb') as f:
            shutil.copyfileobj(r, f)

files = [("newsbreak128.mp3","new_name_1.mp3"), ("toh35.mp3","new_name_1.mp3")]
for file in files:
    download(file)

推荐阅读