【问题标题】:Automatically changing name of downloaded files using Python使用 Python 自动更改下载文件的名称
【发布时间】:2016-03-12 22:35:56
【问题描述】:

此脚本循环遍历下载 csv 文件的 url 列表:

#!/usr/bin/python

import subprocess

file = open('links20151111.txt','r')
for url in file:
        print ('[+] downloadin ' + url.strip())
        subprocess.call(['wget', '--content-disposition', url.strip()])

网址不包含文件名。

需要做的是将文件名中的所有“-”替换为“_”。 文件名可能是这样的,“traffic_injuries_2001-2014.csv”。

【问题讨论】:

  • 您的示例不会将“全部”-s 替换为 _s,只是前两个。你能更准确地定义这个要求吗?

标签: python replace


【解决方案1】:

如果我对问题的理解正确,您可以在每次下载新文件时循环浏览下载目录中的文件并查找其中包含破折号的文件,然后对该文件进行字符替换。应该这样做:

#!/usr/bin/python
import subprocess, os

def rename_file():
    for f in os.listdir(os.getcwd()): 
        if '-' in f and f.endswith('.csv'): 
            os.rename(f,f.replace('-','_'))

file = open('links20151111.txt','r')
for url in file:
        print ('[+] downloadin ' + url.strip())
        subprocess.call(['wget', '--content-disposition', url.strip()])
        rename_file()

根据文件名的结构,您可能需要收紧文件搜索条件。您可以编译正则表达式以更严格地匹配文本格式。

【讨论】:

  • 我用这个代码解决了这个问题:#!/usr/bin/python import os path = os.getcwd() filenames = os.listdir(path) for filename in filenames: os.rename(os.path.join(path, filename), os.path.join(path, filename.replace('-', '_'))) 谢谢你的启发。
【解决方案2】:

使用-O 选项:

wget google.com -O foo.html

更多信息here

否则我建议使用requests 模块:How to download image using requests

【讨论】:

    猜你喜欢
    • 2011-02-06
    • 2020-09-17
    • 2021-12-15
    • 2021-09-22
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多