我正在尝试第9章中的第二个实践项目,使用Python自动处理无聊的东西,但是即使它打印出预期的字符串,它也不能执行取消链接操作系统(filename)命令,文件不会被删除,它们仍然保持原样。有人能帮忙吗?以下是我使用的代码:
#! python3
# deleteUnneeded.py - Searches and deletes files and folders
# to free up space on a computer
import os
# Define a function
def delUnneeded(folder):
folder = os.path.abspath(folder)
# Walk the folder tree with os.walk()
# and search for files and folders of more than 100MB using os.path.getsize()
for foldername, subfolders, filenames in os.walk(folder):
for filename in filenames:
fileSize = os.path.getsize(foldername + '\\' + filename)
if int(fileSize) < 100000000:
continue
os.unlink(filename)
print('Deleting ' + filename + '...')
delUnneeded('C:\\Users\\DELL\\Desktop\\flash')
print('Done')
这就是我解决这个问题的方法,因为这个问题只要求列出大于100MB的文件,所以我们可以跳过删除部分。在
此代码是问题所在:
在调用
os.unlink
之前,有一个continue
语句,它跳到循环的下一个迭代。在我想你是想让
^{pr2}$os.unlink
超出这个条件。只是没有发现:更新
正如上面的注释所指出的,您还需要构建一个完整的路径:
更新2
您可以反转条件的逻辑以简化代码,而不是
if ...: continue
。以下是我清理后的代码版本:其他细微变化:
int(...)
,因为os.path.getsize
已经返回了一个int
。在os.walk
生成的组件组成。在os.walk
文档和Python编码风格(snake_case
而不是camelCase
)。在str.format
而不是字符串连接。在相关问题 更多 >
编程相关推荐