使用os重命名基于python中的变量重命名文件

时间:2018-08-27 08:27:06

标签: python variables wget file-rename

我正在尝试找出如何将下载的文件从NWZV1WB重命名为HENRY。我敢打赌,现在wget看到它以NWZV1WB的形式下载。

重要说明:文件末尾总是数字 NWZV1WB-1.jpg NWZV1WB-2.jpg NWZV1WB-3.jpg

我的代码如下:(Henry yuan-帮助了我)

import wget
import os
import multiprocessing


def run_process(url, output_path):
    wget.download(url, out=output_path)


if __name__ == '__main__':
    cpus = multiprocessing.cpu_count()
    max_pool_size = 4
    pool = multiprocessing.Pool(cpus if cpus < max_pool_size else max_pool_size)
    base_dir = os.path.dirname(os.path.abspath(__file__))
    prefix_list = ["NWZV1WB"]
    folder_name_list = ["HENRY"]  
    download_list = []
    name_list = list(range(1, 7))
    for index, prefix in enumerate(prefix_list):  # return index and item
        folder_name = folder_name_list[index]  # changed
        path = os.path.join(base_dir)
        if not os.path.exists(path):
            os.mkdir(path)
        if not os.path.isdir(path):
            exit()
        for name in name_list:
            download_list.append(['https://example.com/{p}-{n}.jpg'.format(n=name, p=prefix), path])

    for url, path in download_list: 
        pool.apply_async(run_process, args=(url, path, ))
    pool.close()
    pool.join()

2 个答案:

答案 0 :(得分:1)

您的问题有点令人困惑,但是我认为通过注释线程,我可以拼凑出您要做什么。当前您的输出是:

Old name:      New name:
NWZV1WB-1.jpg  NWZV1WB-1.jpg

Desired output is:
NWZV1WB-1.jpg  HENRY-1.jpg

您的新文件名将进入下载列表的path变量中。试试这个:

for name in name_list:
    path = 'your path'
    newfile = path + folder_name +'-{n}.jpg'.format(n=name)
    download_list.append(['https://example.com/{p}-{n}.jpg'.format(n=name, p=prefix), newfile])

答案 1 :(得分:1)

罪魁祸首在这一行:

path = os.path.join(base_dir)

正如您在source code中所见,当只有一个参数join方法简单地返回它时(这可能不是您想要的)。

def join(a, *p):
    """Join two or more pathname components, inserting '/' as needed.
    If any component is an absolute path, all previous path components
    will be discarded."""
    path = a
    for b in p:
        ...
    return path

Cody已经为您提供了答案,我将使用Python 3.6+ f-strings使它变得更干净。

for name in name_list:
    file_path = os.path.join(base_dir, f'{folder_name}-{name}.jpg')
    download_list.append([f'https://example.com/{prefix}-{name}.jpg', file_path])