[英]Python delete file if it has a specific size in bytes
基本上是嘗試查看文件夾中的 1000 多個文件,並刪除任何重復的大小。 我的方法是一次遍歷整個文件夾,刪除具有在前一個文件中看到的確切字節大小的文件。
我嘗試以各種方式編寫它以使其工作,但我一直以同樣的錯誤告終,即找不到指定的文件,並列出了它所在的文件的名稱。
import os
def cleanup():
sizes = [1,2,3] #in bytes
for fileName in os.listdir(r"C:\Users\Jake\Desktop\testing"): #iterate through all items in directory
fileDIR = (r"C:\Users\Jake\Desktop\testing" + "\\" + fileName)
fileSize = os.path.getsize(fileDIR) # get integer value size in bytes of the file
for i in sizes: #compare the size of the current focused file to the items in the list
if fileSize == i:
os.remove(fileName) #If the filesize has been seen before, delete the given file. If not, add the size and go on to next file.
else:
sizes.append(fileSize)
cleanup()
似乎這與您迭代sizes
列表的方式有關。
對於您找到的每個file
,您都在遍歷整個列表,並多次附加大小。
for i in sizes:
如果遇到列表末尾之前的大小,即使文件已匹配並被刪除,也會導致您進行迭代。
你可以,如果只是檢查改變這種情況, size
被發現in
sizes
。
sizes = []
for filename in os.listdir(r"c:\users\admin\storage\\"):
file = r"c:\users\admin\storage\\" + filename
size = os.path.getsize(file)
if size in sizes:
print('same size', filename)
else:
sizes.append(size)
我第一次在我自己的文件夾上運行它時,它返回;
same size static
same size storage
sizes
#[0, 4096, 135168, 554, 102]
這正確匹配,因為static
和storage
是 0 字節。 當我再次運行它時,沒有修改每個文件匹配的sizes
結果。
same size .ebextensions
same size customer
same size db.sqlite3
same size manage.py
same size requirements.txt
same size static
same size storage
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.