繁体   English   中英

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

[英]Rename multiple files in a local folder by a specific order in python

我想通过特定的顺序重命名多个 python 文件:

我当前的 output 文件名是

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

但是想要的 output 文件名应该是这样的:

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___c.tile.opentopomap.org_16_34309_22369

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

我认为您打算再次将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)

为什么不直接切换 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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM