亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法在python中刪除部分文件名(路徑)?

有沒有辦法在python中刪除部分文件名(路徑)?

慕勒3428872 2022-10-25 14:56:25
我有大約 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.renamePath.with_namePath.name,str.replace


查看完整回答
反對 回復 2022-10-25
?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

file = 'directory/imagehellohellohello.png'

keyword = 'hello'

if keyword*3 in file:

   newname = file.replace(keyword*3, '')

   os.rename(file, newname)


查看完整回答
反對 回復 2022-10-25
  • 2 回答
  • 0 關注
  • 210 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號