用於截圖時間資料,需要批量更改檔名並以數字依序遞增。
簡介 os
os.path.abspath(‘.’) 列印絕對路徑
os.path.join(a, b) –> a/b 拼接路徑
os.path.split(a/b) –> 這樣可以把一個路徑拆分為兩部分,後一部分總是最後級別的目錄或檔名
os.path.splitext() –>得到檔案擴充名
os.rename() –> 對檔案重新命名
os.remove() –> 刪除檔案
os.path.dirname() –>獲取檔案或資料夾的路徑
os.path.isfile/os.path.isdir() –>確認是檔案或者資料夾
os.walk() –>遍歷目錄,return (dirpath, dirnames, filenames).
dirpath 是以 string 字串形式返回該目錄下所有的絕對路徑;
dirnames 是以列表 list 形式返回每一個絕對路徑下的資料夾名字;
filesnames 是以列表 list 形式返回該路徑下所有檔名字。
Coding
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import os import time
def modi_dataname(dirpath): localtime = time.localtime() result = time.strftime("%m%d-%H", localtime) length = 0 filesnames = [] for dirpath, dirnames, filesnames in os.walk(dirpath): length = len(filesnames) for i in range(length): num = str(i).zfill(1) filename = "擷取-"+result+"00-"+num scrfilename = dirpath + "\\" + filesnames[i] nowfilename = dirpath + "\\" + filename + ".png" try: os.rename(scrfilename, nowfilename) except Exception as e: print('rename file fail\r\n') else: print('rename file successfullly\r\n')
if __name__ == '__main__': path = os.path.abspath('C:\\Users\\admin\\Pictures\\Screenshots') modi_dataname(path)
|
引用文章