在不更改实际编号顺序的情况下重命名 python 中的文件名?
Renaming filenames in python without changing the actual number order?
我有这样的文件:
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)
您有一个源目录(其中包含 badly/identical 命名文件)和一个目标目录(其中包含不应被覆盖的文件)。
我会:
- 列出目标目录并像您一样排序(您的其余尝试显然是错误的...)
- 获取最后一项并解析为整数(无扩展名):加 1 并给出下一个空闲索引。
- 在源目录中循环
- 使用新的计算索引为当前文件生成一个新名称
- 使用
shutil.move
或shutil.copy
来move/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))
你可以这样做:
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
重命名并将文件从第一个目录移动到第二个目录。
我有这样的文件: 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)
您有一个源目录(其中包含 badly/identical 命名文件)和一个目标目录(其中包含不应被覆盖的文件)。
我会:
- 列出目标目录并像您一样排序(您的其余尝试显然是错误的...)
- 获取最后一项并解析为整数(无扩展名):加 1 并给出下一个空闲索引。
- 在源目录中循环
- 使用新的计算索引为当前文件生成一个新名称
- 使用
shutil.move
或shutil.copy
来move/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))
你可以这样做:
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
重命名并将文件从第一个目录移动到第二个目录。