【问题标题】:Renaming filenames in python without changing the actual number order?在不更改实际数字顺序的情况下重命名python中的文件名?
【发布时间】:2018-06-27 14:38:10
【问题描述】:

我有如下文件: 00001.jpg 00002.jpg . . . 01907.jpg

我想在这个目录中添加一些同名的文件。但他们的名字应该继续像 01908.jpg 01909.jpg . . 12906.jpg

我无法做到这一点。我怎样才能做到这一点?

非常感谢:)

我试过了

import os 
files=[]

files = sorted(os.listdir('directory'))
b=len(files)
for i in range(0,b):
    a=files[i]

    os.rename(a,(a+1))

print (files)

【问题讨论】:

  • 到现在为止你尝试了什么?
  • 列出目录,获取最后一个文件,计算起始索引,重命名复制。试试看。
  • 我编辑了帖子。
  • 现在尝试投下 4 票(甚至是微弱的)?加油!

标签: python renaming


【解决方案1】:

您有一个源目录(其中包含错误/相同命名的文件)和一个目标目录(其中包含不应被覆盖的文件)。

我愿意:

  • 列出目标目录并像您所做的那样进行排序(您的其余尝试显然已关闭...)
  • 获取最后一项并解析为整数(不带扩展名):加 1 并给出下一个空闲索引。
  • 在源目录中循环
  • 使用新计算的索引为当前文件生成一个新名称
  • 使用shutil.move 或shutil.copy 以新名称移动/复制新文件

像这样:

import os,shutil

s = "source_directory"
d = "target_directory"
files = sorted(os.listdir(d))

highest_index = int(os.path.splitext(files[-1])[0])+1

for i,f in enumerate(sorted(os.listdir(s)),highest_index):
    new_name = "{:05}.png".format(i)
    shutil.copy(os.path.join(s,f),os.path.join(d,new_name))

【讨论】:

    【解决方案2】:

    你可以这样做:

    import os
    directory1 = 'path to the directory you want to move the files to'
    directory2 = 'path to the directory you want to move the files to'
    
    for file in ordered(os.listdir(directory2)):
        counter = len(os.listdir(directory1))
        file_number = int(file.split('.')[0]) #Get the file number
        os.rename(os.path.join(directory2, file), os.path.join(directory1 + str(file_number + counter)))
    

    我做了什么:

    • 循环遍历我想要重命名和移动的文件。
    • 在将要移动文件的主目录中找到文件数,我认为它与此目录中最后一个文件的名称相同,并确保它会保留更新自身,以免发生覆盖。
    • 然后我得到了循环中当前文件的编号。
    • 最后,我使用os.rename 重命名并将文件从第一个目录移动到第二个目录。

    【讨论】:

    • 加:目录2 + 文件很难看。使用 os.path.join
    • 注意到了,只是想写点简单的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2011-12-12
    • 2021-05-26
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多