如何在Python中重命名子目录?

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

我看到一些帖子询问如何重命名子目录,特别是这个,我想对子子目录做类似的事情。我正在制作一个不能有子子目录的数据集。到目前为止,这是我尝试过的大纲:

'''
In the data/ directory,
For each subdirectory
    For each sub-subdirectory
        Rename it to '{sub_dir}_{subsub_dir}' # So I know which subdir the subsubdir came from
        Take the subsub_dir out of the sub_dir, and place it in 'data/'
    After the inner loop, the subdir should be empty and we can remove it
'''

PATH = r'data' # Relative path
for s in os.listdir(PATH):
    subdir_path = os.path.join(PATH, s)
    for ss in os.listdir(subdir_path):
        pprint(f'Before: {ss}')
        ss = f'{s}_{ss}' # 
        pprint(f'After: {ss}')
        os.rename(os.path.join(subdir_path, ss), os.path.join(PATH, ss))
    # os.remove(subdir_path) # Commented out for safety
如果有影响的话,

data
是相对路径。 VSCode 有一个选项,我可以复制文件夹的相对路径,所以我没有手动写出来。

但是,当我尝试这个时,我得到:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'data\\1\\1_1' -> 'data\\1_1'

'data\\1_1'
是我想要将子子目录重命名为的内容(因此它们成为子目录)。我认为只做我链接的帖子中描述的相同的事情,但在嵌套循环中不会有什么不同,但我得到了这个错误。

我哪里出错了?

python subdirectory
1个回答
0
投票

在实际更改之前,您正在将

ss
的变量重写为新文件名。通常,在
for
循环中,您不想更改保存迭代值的变量,在本例中为
ss

而是创建一个新变量来保存您要使用的新名称:

PATH = r'data' # Relative path
for s in os.listdir(PATH):
    subdir_path = os.path.join(PATH, s)
    for ss in os.listdir(subdir_path):
        pprint(f'Before: {ss}')
        new_ss = f'{s}_{ss}' # 
        pprint(f'After: {new_ss}')
        os.rename(os.path.join(subdir_path, ss), os.path.join(PATH, new_ss))
© www.soinside.com 2019 - 2024. All rights reserved.