我想要删除文件夹中的所有空文件,该文件夹内还有其他文件夹,所以需要检查这些文件夹内部:
例如,在C:\ folder1 \ folder1和C:\ folder1 \ folder2等文件夹中删除所有空文件。
例如,在C:\ folder1 \ folder1和C:\ folder1 \ folder2等文件夹中删除所有空文件。
import sys
import os
def main():
getemptyfiles(sys.argv[1])
def getemptyfiles(rootdir):
for root, dirs, files in os.walk(rootdir):
for d in ['RECYCLER', 'RECYCLED']:
if d in dirs:
dirs.remove(d)
for f in files:
fullname = os.path.join(root, f)
try:
if os.path.getsize(fullname) == 0:
print fullname
os.remove(fullname)
except WindowsError:
continue
os.remove()
可能会失败,因此最好也将其包装在try...except
语句中。 WindowsError
是特定于平台的。过滤遍历的目录不是必要的,但是有帮助的。import os
while(True):
path = input("Enter the path")
if(os.path.isdir(path)):
break
else:
print("Entered path is wrong!")
for root,dirs,files in os.walk(path):
for name in files:
filename = os.path.join(root,name)
if os.stat(filename).st_size == 0:
print(" Removing ",filename)
os.remove(filename)
cd /d C:\folder1
for /F "usebackq" %%A in (`dir/b/s/a-d`) do (
if %%~zA LSS 1 del %%A
)
我首先删除了空文件,然后按照这个答案(https://dev59.com/b2025IYBdhLWcg3wHR4Y#6215421)的方法,我删除了空文件夹。
此外,我在os.walk()
中添加了topdown=False
,以从叶子到根遍历,因为os.walk()
的默认行为是从根到叶子遍历。
因此,也会删除包含空文件夹或文件的空文件夹。
import os
def remove_empty_files_and_folders(dir_path) -> None:
for root, dirnames, files in os.walk(dir_path, topdown=False):
for f in files:
full_name = os.path.join(root, f)
if os.path.getsize(full_name) == 0:
os.remove(full_name)
for dirname in dirnames:
full_path = os.path.realpath(os.path.join(root, dirname))
if not os.listdir(full_path):
os.rmdir(full_path)
希望这能对你有所帮助
#encoding = utf-8
import os
docName = []
def listDoc(path):
docList = os.listdir(path)
for doc in docList:
docPath = os.path.join(path,doc)
if os.path.isfile(docPath):
if os.path.getsize(docPath)==o:
os.remove(docPath)
if os.path.isdir(docPath):
listDoc(docPath)
listDoc(r'C:\folder1')
==o
替换为 ==0
。 - nealmcb
RECYCLER
或RECYCLED
的文件夹。 - alper