import
os
def
batch_rename(folder_path, prefix
=
"document"
, keep_extension
=
True
, sort_key
=
None
):
try
:
files
=
[f
for
f
in
os.listdir(folder_path)
if
os.path.isfile(os.path.join(folder_path, f))]
if
sort_key:
files.sort(key
=
sort_key)
else
:
files.sort()
success_count
=
0
skipped_count
=
0
for
idx, filename
in
enumerate
(files, start
=
1
):
old_path
=
os.path.join(folder_path, filename)
if
filename.startswith(
'~$'
):
skipped_count
+
=
1
continue
base, ext
=
os.path.splitext(filename)
new_name
=
f
"{prefix}_{idx:03d}"
if
keep_extension:
new_name
+
=
ext
new_path
=
os.path.join(folder_path, new_name)
try
:
counter
=
1
while
os.path.exists(new_path):
new_name
=
f
"{prefix}_{idx:03d}_{counter}{ext}"
new_path
=
os.path.join(folder_path, new_name)
counter
+
=
1
os.rename(old_path, new_path)
print
(f
"重命名成功: {filename} -> {new_name}"
)
success_count
+
=
1
except
Exception as e:
print
(f
"错误: 无法重命名 {filename} - {str(e)}"
)
print
(f
"\n操作完成!成功重命名 {success_count} 个文件,跳过 {skipped_count} 个文件"
)
except
Exception as e:
print
(f
"发生错误: {str(e)}"
)
if
__name__
=
=
"__main__"
:
target_folder
=
"F:\\工作文件\\临时\\demo001"
batch_rename(
folder_path
=
target_folder,
prefix
=
"report"
,
keep_extension
=
False
,
sort_key
=
None
)