在python中按特定顺序重命名本地文件夹中的多个文件

2024-09-28 18:51:29 发布

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

我想按特定顺序重命名多个python文件:

我当前的输出文件名是

e.g. https___c.tile.opentopomap.org_16_j_i (e.g. https___c.tile.opentopomap.org_16_34309_22369) 

但是想要的输出文件名称应该如下所示:

e.g. https___c.tile.opentopomap.org_16_i_j (e.g. https___c.tile.opentopomap.org_16_22369_34309) 

到目前为止,我在代码中没有看到错误:

import requests
import multiprocessing
import pprint
import time

print("The pictures will be saved all what is east-south from Mannheim Quadrate")
x2 = int(input("North-South (latitude) (start: 22369): "))
x3 = int(input("East-West (longitude) (start: 34309): "))
urls = [
    f"https://c.tile.opentopomap.org/16/{j}/{i}.png" for i in range(22369, x2 + 1) for j in range(34309, x3 + 1)]

def download_image(url):
    response = requests.get(url)
    splitted_url = url.split("/")
    last_part = splitted_url[-1].replace(".png", "")
    second_to_the_last = splitted_url[-2]
    splitted_url[-1] = second_to_the_last
    splitted_url[-2] = last_part

    print(f"Downloading from {url}...")
    url = url.replace("/", "_").replace(":", "_")
    with open(f"{url}", "wb") as file:
        file.write(response.content)

    print(f"Downloading from {url}...")
    url = url.replace("/", "_").replace(":", "_")
    with open(f"{url}", "wb") as file:
        file.write(response.content)

if __name__ == "__main__":
    start = time.perf_counter()
    p = multiprocessing.Pool(processes=4)
    p.map(download_image, urls)
    p.close()
    stop = time.perf_counter()


    print(f"It took {round(stop - start, 2)} seconds in total")

该部分应完成以下工作:

    splitted_url = url.split("/")
    last_part = splitted_url[-1].replace(".png", "")
    second_to_the_last = splitted_url[-2]
    splitted_url[-1] = second_to_the_last
    splitted_url[-2] = last_part

但它不起作用。文件名的顺序仍然错误(例如https\uuuuu c.tile.opentopomap.org\u 16\u 34309\u 22369

我不知道为什么它不切换文件名的最后部分。有人知道吗


Tags: thetohttpsorgimporturlstartreplace
2条回答

为什么不直接切换i和j呢

urls = [ f"https://c.tile.opentopomap.org/16/{j}/{i}.png" for i in range(22369, x2 + 1) for j in range(34309, x3 + 1)]

变成:

urls = [ f"https://c.tile.opentopomap.org/16/{i}/{j}.png" for i in range(22369, x2 + 1) for j in range(34309, x3 + 1)]

我想你是想把splitted_url重新组合在一起:

splitted_url[-1] = second_to_the_last
splitted_url[-2] = last_part
url = '_'.join(splitted_url)    # join the parts together

print(f"Downloading from {url}...")
url = url.replace("/", "_").replace(":", "_")
with open(f"{url}", "wb") as file:
    file.write(response.content)

相关问题 更多 >