当文件具有相同名称时,如何在for循环中重命名下载的文件?

2024-09-20 22:54:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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,使其能够适应同名但末尾有数字的文件的问题。例如:Data(1).csv,Data(2).csv,Data(3).csv

谢谢


Tags: 文件csv数据fromimportsenddataselenium
2条回答

如果您知道文件的顺序(即,您知道数据(1)应命名为中国数据,数据(2)应命名为巴西数据等),那么您只需使用列表并根据列表重命名所有文件

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')

您可以在末尾使用正确的\u名称列表调用重命名\u文件

因为您知道下载文件的名称,所以可以随时重命名。要知道下载何时完成可能很困难,所以我使用了轮询方法

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))

相关问题 更多 >

    热门问题