刪除路徑裡相同檔名的文件
刪除路徑裡相同檔名的文件
前言
有時候好學的我,上的課程越來越多,文件,視頻也跟著堆在筆電裡
越來越豐富,但有時候其實都已經重覆接收和下載這些電子文件
,趁著中秋節連假到來,練習一下這個好用的辦公室自動化來清理
重覆且暫空間的程式。
會用到的模塊有
os
glob
filecmp
模塊的介紹
glob
glob.glob(pathname, *, recursive=bool)
如果 recursive 为真值,则模式 "**" 将匹配目录中的任何文件以及零个或多个目录、子目录和符号链接。
filecmp
filecmp.cmp(f1, f2, shallow=True)True ,否则返回 False 。os
os.path.exists(path)如果 path 指向一个已存在的路径或已打开的文件描述符,返回 True。对于失效的符号链接,返回 False。在某些平台上,如果使用 os.stat() 查询到目标文件没有执行权限,即使 path 确实存在,本函数也可能返回 False
import os, glob, filecmp
dirPath=r'D:\test'
#fileList=[]
for i in glob.glob(dirPath+'/\**/\*', recursive=True):
print(i)
PS D:\python> & C:/Python38/python.exe d:/python/test2.py
D:\test\GPL-2
D:\test\uPyCraft.exe
D:\test\Win32DiskImager.exe
D:\test\新增資料夾
D:\test\新增資料夾\Win32DiskImager.exe
在glob.glob()裡'\**\*',意思是批配層層的資料夾,請見上方模塊介紹
接下來設製一個fileList的空list,把批配出來並且確認是檔案的檔加入fileList裡
看看發生了什麼
import os, glob, filecmp
dirPath=r'D:\test'
fileList=[]
for i in glob.glob(dirPath+'/\**/\*', recursive=True):
if os.path.isfile(i):
fileList.append(i)
print(fileList)
PS D:\python> & C:/Python38/python.exe d:/python/test2.py
['D:\\test\\GPL-2', 'D:\\test\\uPyCraft.exe',
'D:\\test\\Win32DiskImager.exe', 'D:\\test\\新增資料夾\\Win32DiskImager.exe']
接著用一個大迴圈一個小迴圈讓檔案比對互相有重覆的檔案
並且最後用filecmp模塊比較兩個迴圈裡的檔案,再用os.remove()刪除
相同的檔案。
import os, glob, filecmp
dirPath=r'D:\test'
fileList=[]
for i in glob.glob(dirPath+'/\**/\*', recursive=True):
if os.path.isfile(i):
fileList.append(i)
for j in fileList:
for s in fileList:
if j != s:
if filecmp.cmp(j, s):
os.remove(s)
但這樣可能會出現錯誤的返回,這時要加入os.path.exists(path)來判斷路徑檔案是
否存在,加入之後如下:
import os, glob, filecmp
dirPath=r'D:\test'
fileList=[]
for i in glob.glob(dirPath+'/\**/\*', recursive=True):
if os.path.isfile(i):
fileList.append(i)
for j in fileList:
for s in fileList:
if j!=s and os.path.exists(j) and os.path.exists(s):
if filecmp.cmp(j, s):
os.remove(s)
執行之後,它就完美刪除重覆的檔案了。
留言
張貼留言