python - 下载后在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)
解决方案
在不过多更改函数的情况下执行此操作的方法是将要下载的文件名的值以及要以字典格式或作为列表中的元组重命名文件的名称传递。我将举一个后者的例子。如果您传递每对名称(要下载的名称及其新名称),然后通过索引指定您要尝试获取的名称,那么您的函数应该可以工作。
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)
推荐阅读
- javascript - Bootstrap 3.3.7 如何点击外部关闭导航栏?
- p5.js - 如何在每个点之间创建一条线?
- javascript - 如何通过一个请求在浏览器中接收和显示多条消息?
- java - Java 的 main() 方法可以声明为 final 吗?
- java - 没有递归的冰雹序列(请)
- html - 下拉菜单流出屏幕
- swift - 通过firebase数据库问题连接到vimeo视频
- laravel - Laravel Eloquent,使用 withTrashed() 返回空关系的多深度点表示法
- ajax - 使用方法 PUT 调用 Laravel AJAX
- java - 将泛型与 JUnit 4 Theories 一起使用时出错