2 回答

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
這可以很簡單地使用pathlib
:
from pathlib import Path
path = Path("directory/imagehellohellohello.png")
target = path.with_name(path.name.replace("hello", ''))
path.rename(target)
這確實(shí)將文件重命名為"directory/image.png".
從 Python 版本 3.8 開始,該rename方法還將新文件的路徑作為Path對象返回。(所以可以這樣做:
target = path.rename(path.with_name(path.name.replace("hello", '')))
使用的方法/屬性:Path.rename
, Path.with_name
, Path.name
,str.replace

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if keyword*3 in file:
newname = file.replace(keyword*3, '')
os.rename(file, newname)
添加回答
舉報(bào)