【问题标题】:How can I rename a downloaded file in a for loop, when files have the same name?当文件具有相同名称时,如何在 for 循环中重命名下载的文件?
【发布时间】:2020-02-27 19:41:07
【问题描述】:

我在 Python 中使用 Selenium 下载相同的文件,但每次使用不同的输入。例如,我下载带有国家选择“中国”的数据。在下一次迭代中,我下载了相同的数据,但针对的是“巴西”国家/地区。

我正在努力寻找易于理解的语法来重命名下载的文件。这些文件目前正在下载为“Data.csv”和“Data(1).csv”。我想要的是“China-Data.csv”和“Brazil-Data.csv”。

我为此构建的唯一相关代码是:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

ChromeOptions=webdriver.ChromeOptions()
driver =webdriver.Chrome('Users/yu/Downloads/chromedriver')

inputcountry.send_keys('China')
inputcountry.send_keys(Keys.RETURN)

我通读了this post,但我不知道如何创建一个 forloop 来适应具有相同名称但末尾有数字的文件的问题。例如:数据(1).csv、数据(2).csv、数据(3).csv

谢谢

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    由于您知道下载文件的名称,因此您可以随时重命名。知道下载何时完成可能很棘手,因此我使用了轮询方法。

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import os
    import time
    import shutil
    
    download_file = os.path.expanduser("~/Downloads/Data.csv")
    save_to_template = os.path.expanduser("~/Documents/Data-{}.csv")
    
    # remove stale files
    if os.path.isfile(download_file):
        os.remove(download_file)
    
    ChromeOptions=webdriver.ChromeOptions()
    driver =webdriver.Chrome('Users/yu/Downloads/chromedriver')
    
    countries = ['China', 'Malaysia', 'Brazil']
    
    for country in countries:
        inputcountry.send_keys(country)
        inputcountry.send_keys(Keys.RETURN)
    
        # one option is to poll for file showing up.... assuming file
        # is renamed when done
        for s in range(60): # give it a minute
            if os.path.exists(download_file):
                shutil.move(download_file, save_to_template.format(country))
                break
        else:
            raise TimeoutError("could not download {}".format(country))
    

    【讨论】:

    • 这在直觉上很有意义。但是直到我在if os.path.exists(download_file) 之后添加了一个冒号之后代码才起作用,以供其他阅读本文的人使用
    • 也应该是shutil.move 而不是os.move?接收错误Attribute Error: module 'os' does not have 'move'
    • @YuNa - 对!固定。
    【解决方案2】:

    如果您知道文件的顺序(即您知道 Data(1) 应该命名为 China-Data,Data(2) 应该命名为 Brazil-Data 等),那么您只需要使用一个列表并根据它重命名所有文件。

    import os 
    
    directory = 'Users/yu/Downloads/chromedriver/'
    correct_names = ['China-Data.csv','Brazil-Data.csv']
    
    def rename_files(directory: str, correct_names: list) -> None: 
        # change the name of each file in the directory
        for i, filename in enumerate(sorted(os.listdir(directory))): 
            src = directory + filename 
            dst = directory + correct_names[i]
            os.rename(src, dst) 
    

    每次您执行inputcountry.send_keys('China') 时,您都可以将您提供的任何输入添加到正确名称列表中,例如correct_names.append('China-Data.csv')

    您可以使用正确的名称列表在末尾调用 rename_files。

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 2022-06-14
      • 1970-01-01
      • 2010-12-29
      • 2013-01-08
      • 2019-06-27
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      相关资源
      最近更新 更多