Python小指令碼 批量修改檔名與副檔名

2021-08-08 14:01:45 字數 1975 閱讀 4311

0x01:修改前後效果對比

修改前:

修改後:

0x02:原始碼

# coding:utf-8

# by landgrey

# function: modify the file name or file postfix

import os

path = r'c:\works\try'

#要修改檔案所處路徑

all_file_list = os.listdir(path) #列出指定目錄下的所有檔案

oldpart = "test"

#要替換的檔名中的部分

newpart = "land"

#新的檔名部分

oldpostfix =r".txt"

#要修改的副檔名型別

newpostfix = r".grey"

#新的副檔名型別

#批量修改檔案名字

defmodifyprefix

(oldcontent,newcontent):

for file_name in all_file_list:

currentdir =os.path.join(path, file_name) #連線指定的路徑和檔名or資料夾名字

if os.path.isdir(currentdir): #如果當前路徑是資料夾,則跳過

continue

fname = os.path.splitext(file_name)[0] #分解出當前的檔案路徑名字

ftype = os.path.splitext(file_name)[1] #分解出當前的副檔名

replname =fname.replace(oldcontent,newcontent)

newname = os.path.join(path,replname+ftype) #檔案路徑與新的檔案名字+原來的副檔名

os.rename(currentdir,newname) #重新命名

print

"modify file name........"

#批量修改副檔名

defmodifypostfix

(oldftype,newftype):

for file_name in all_file_list:

currentdir =os.path.join(path,file_name)

if os.path.isdir(currentdir): #跳過資料夾

continue

fname = os.path.splitext(file_name)[0]

ftype = os.path.splitext(file_name)[1]

if ftype ==oldftype: #找到需要修改的副檔名

newname = os.path.join(path,fname+newftype) #檔案路徑與原來的檔案名字+新的副檔名

os.rename(currentdir,newname) #重新命名

print

"modify file postfix...... "

modifyprefix(oldpart,newpart)

modifypostfix(oldpostfix,newpostfix)

print

"finished !"

0x03:說明

詳細的解說見注釋。

由於部落格改變了文字原縮排格式,雖我也盡力預覽博文修改了,但還是請注意原始碼中的縮排。

共有兩個不同的函式對應兩個不同的功能,用到哪個最後就呼叫哪個,不用的那個函式就用「#」注釋掉好了。

python批量修改檔案指令碼

最近在做訓練集,好多未排序,記錄一下重新命名的 import osimport reimport sys 以下為目標資料夾與當前資料夾相同的示例 defrename filelist os.listdir r d file label 當前 資料夾,儲存檔案的資料夾 currentpath os.g...

python檔案命名小指令碼

寫個檔案命名的python程式,復 yu 習一下python。程式寫得應該不是很好。import os import shutil from pil import image 輸入為路徑 命名方式為統一位數數字遞增 單一檔案格式查詢 輸出為 result.txt 檔名,是否為完整 full 完整庫 ...

python小指令碼

匹配文件內容的關鍵字,並取得該關鍵字所在行所有內容 find the row where need keyword def getcontent tfile,sstr global keyword f1 open tfile readlines for i,j in enumerate f1 if ...