将 PNG 文件名与 JSON 文件名关联并随机化

问题描述 投票:0回答:1

我的文件夹中有 PNG 和 JSON 文件,其名称编号从 1 到 1000。换句话说,我有 2000 个文件。 PNG 文件通过名称中的数字与 JSON 文件进行匹配。例如15.png的信息在15.json中。我想要做的是随机重命名这些文件,同时保持 png 文件与 json 文件的关联。例如,我想将 15.png 重命名为 321.png,这意味着将 15.json 重命名为 321.json。为了防止使用文件夹中已有的数字,最好将 png 及其 json 复制到新文件夹,然后为这两个文件分配一个随机数字/名称(1 到 1000 之间)并重复该过程。我尝试过使用 .split、.startswith 和 .结束功能但遇到困难。非常感谢任何见解。

python rename copying
1个回答
0
投票

我无法判断这是否是最优雅或最高效的方法,但您可以尝试以下方法:

# Import some modules from the standard library
import pathlib
import random
import shutil


# Specify the directory that contains your original files.
data_directory = pathlib.Path('./')

# Specify the name of the directory where the renamed files are going
# to be stored.
new_directory = pathlib.Path('./new')

# Create the new directory, if it does not exist, yet.
new_directory.mkdir(exist_ok=True)

# Create a list of all png files in the directory given above using a
# list comprehension.
# Pitfall: Please note that the suffix attribute contains a leading dot,
# i.e. using suffix == 'png' would return an empty list.
original_files = [
    item for item in data_directory.iterdir()
    if item.suffix == '.png'
]

# Create a copy of your list of files and shuffle it randomly.
new_names = original_files.copy()
random.shuffle(new_names)

# Loop over both file lists simultaneously and get the name of the file
# to copy from the first one, and derive it's destination from the second 
# one.
for old, new in zip(original_files, new_names):
    shutil.copy(old, new_directory.joinpath(new))

要移动 json 文件,您只需在循环中添加一行,但我将让您自行解决这一问题。它涉及路径对象上可用的 .with_suffix 方法。

© www.soinside.com 2019 - 2024. All rights reserved.