Python 复制现有文件并将名称递增 1 n 次

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

我正在尝试获取一个现有文件,假设 0.json 中包含一些代码。然后我需要复制文件,将其重命名为 1.json,保留这两个文件,然后再次执行相同的过程 x 次,每次复制文件时递增 1。

这是我试过的。我知道这是不正确和不完整的(这段代码甚至没有调用复制或重命名)但是,我现在只是在学习“for 循环”并且在每个阶段都被卡住了。

import os
import shutil

#This is getting the current working directory
print(os.getcwd())

#This is changing the directory from above
os.chdir('[INSERT PATH]')

#trying to copy file and then increment the name by +1 each copy and run for a specified range
for file in os.listdir():
    name, ext = os.path.splitext(file)
    value = int(name)
    for i in range (0,10):
            i += 1
    new_name = f"{i}{ext}"
python for-loop iterator copy shutil
3个回答
0
投票

您需要更改

for
循环中的逻辑以将文件名增加 1:

for file in os.listdir():
    name, ext = os.path.splitext(file)
    value = int(name)
    newname = f"{value + 1}.{ext}"
    shutil.copyfile(file, newname)

文件只会被复制一次。当您调用

os.listdir()
时,它会在那一刻 在当前工作目录中创建一个文件列表。然后代码一个一个地遍历该列表,获取每个文件并创建一个副本,文件名递增 1。由于新创建的文件一开始不在目录中,因此它们不会添加到正在迭代的列表。因此,例如,假设 CWD 包含
1.json
13.json
42.json
。上面的代码运行后,它将包含
1.json
,
2.json
,
13.json
,
14.json
,
42.json
, and
43.json
.


您的新要求是从一个输入文件创建 10,000 个相同的文件。以下是如何做到这一点:

for file in os.listdir():
    name, ext = os.path.splitext(file)
    value = int(name)
    for i in range(value+1, value+10001):
        newname = f"{i}.{ext}"
        shutil.copyfile(file, newname)

0
投票

应该很明显,但在运行任何这些答案之前进行备份。还应该指出,如果你多次运行它,那么它会为目录中的每个

n
文件制作一个新副本。大多数会被新文件覆盖,但从最后一个索引开始,每次运行最终会多“n”个。所以只运行一次!

def do_copy(root, n_times):
    assert os.path.exists(root)
    os.chdir(os.path.join(os.getcwd(), root))
    for file in os.listdir(os.curdir):
        if not os.path.isfile(file):  # only change names if it's a file
            continue
        name, ext = os.path.splitext(file)
        start_ind = int(name)
        for n in range(1, n_times):
            new_file = os.path.join(os.getcwd(), f"{start_ind+n}{ext}")
            shutil.copy(os.path.join(os.getcwd(), file), new_file)


do_copy("so_help\\A", 2)

0
投票

我们查看了上面的回复,发现上面函数的一些返回语句存在一些问题。尽管它们确实有助于为下面的代码建立一个可靠的框架。答案是获取目录、解析名称和扩展名、递增名称的混合(文件的名称是“0.json”;如果它更复杂,您需要合并另一个解析器),

下面的函数/解决方案的缺点之一是“复制”参数依赖于使用“.”的当前目录。作为论据。当输入目录路径作为参数时,出现了一些错误。

import os
import shutil

def do_copy(dir_path, n_times):
    assert os.path.exists(dir_path)
    os.chdir(os.path.join(os.getcwd(), dir_path))
    for file in os.listdir(os.curdir):
        if not os.path.isfile(file) or file [0] == ".":  # only change names if it's a file or not a .file
            continue
        name, ext = os.path.splitext(file)
        print("This is the original file name: ", name)
        start_ind = int(name)
        for n in range(1, n_times+1):
            new_file = os.path.join(os.getcwd(), f"{start_ind+n}{ext}")
            shutil.copy(os.path.join(os.getcwd(), file), new_file)

            
do_copy('.', 5) #'.' works from the current directory and the second argument states how many copies to make
© www.soinside.com 2019 - 2024. All rights reserved.