Переименуйте несколько файлов в локальной папке, указав c порядок в python - PullRequest
0 голосов
/ 13 апреля 2020

я хочу переименовать несколько python файлов по указанному c порядку:

Мое текущее имя выходного файла:

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

Но требуемый выходной filenaem должен выглядеть следующим образом :

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

Я не знаю, почему он не переключает последние части имени файла. У кого-нибудь есть идея?

Ответы [ 2 ]

1 голос
/ 14 апреля 2020

Я думаю, вы хотели снова присоединиться к 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)
0 голосов
/ 14 апреля 2020

почему бы просто не переключить 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)]

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...