我有大約 50 個文件,它們的名稱和創建日期分別為 3 次。如何從 python 中的文件名中刪除該部分(您可以展示一個包含其他數據的示例,這并不重要)我嘗試過這樣的事情:file = 'directory/imagehellohellohello.png'keyword = 'hello'if (file.count(keyword) >= 3): //functionality (here I want to remove the hello's from the file path)
2 回答

慕村225694
TA貢獻1880條經驗 獲得超4個贊
這可以很簡單地使用pathlib
:
from pathlib import Path
path = Path("directory/imagehellohellohello.png")
target = path.with_name(path.name.replace("hello", ''))
path.rename(target)
這確實將文件重命名為"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貢獻1816條經驗 獲得超6個贊
file = 'directory/imagehellohellohello.png'
keyword = 'hello'
if keyword*3 in file:
newname = file.replace(keyword*3, '')
os.rename(file, newname)
添加回答
舉報
0/150
提交
取消