如何根据字符串重命名文件?

2024-06-16 11:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码用硬编码文件名重命名文件。当然日期可以改变。你知道吗

import shutil 
# Source path 
source = "C:\\WeeklyReports\\temp\\we mmddyy_DONE.xlsx"

# Destination path 
destination = "C:\\WeeklyReports\\we 101219.xlsx"

# Copy the content of 
# source to destination 
shutil.copyfile(source, destination) 

如何替换源文件名中的mmddyy(we mmddyy)_完成.xlsx)字符串格式为\u mmddyy,如下所示?你知道吗

format_mmddyy
'100619'

type(format_mmddyy)
str

Tags: 文件path代码importformatsource编码文件名
1条回答
网友
1楼 · 发布于 2024-06-16 11:19:36

您可以使用str.replace函数

import shutil 
# Source path 
source = "C:\\WeeklyReports\\temp\\we mmddyy_DONE.xlsx"
format_mmddyy = 100619
destination = source.replace('mmddyy_DONE', format_mmddyy)

shutil.copyfile(source, destination) 

相关问题 更多 >