第9章,使用Python练习项目自动化无聊的东西:删除不需要的文件



我正在尝试使用Python自动化无聊的东西的第9章中的第二个练习项目,但即使它打印了预期的字符串,它也不会执行OS.unlink(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')

此代码是问题:

if int(fileSize) < 100000000:
    continue
    os.unlink(filename)

在致电os.unlink之前,您有一个continue语句,该语句跳到循环的下一个迭代。

我认为您的意思是在此条件外的os.unlink。只是不知道:

if int(fileSize) < 100000000:
    # skip small files
    continue
# Otherwise, delete the file
os.unlink(filename)

update

正如上面评论中指出的那样,您还需要构建一个完整的路径:

os.unlink(os.path.join(foldername, filename))

更新2

而不是if ...: continue,您可以逆转条件的逻辑以简化代码。这是我的代码清理版本:

import os
def del_unneeded(folder):
    # Walk the folder tree with os.walk() and search for files of more than
    # 100MB using os.path.getsize()
    for dirpath, dirnames, filenames in os.walk(folder):
        for filename in filenames:
            full_path = os.path.join(dirpath, filename)
            if os.path.getsize(full_path) > 100000000:
                print('Deleting {}...'.format(full_path))
                os.unlink(full_path)
del_unneeded('C:\Users\DELL\Desktop\flash')
print("Done")

其他较小的更改:

  • 我丢弃了int(...),因为os.path.getsize已经返回int
  • 我使用了一条完整的路径,该路径是由os.walk所产生的组件形成的。
  • 我重命名了一些变量以符合os.walk文档和Python编码样式(snake_case而不是camelCase)。
  • 我使用str.format而不是字符串串联。

这就是我解决这个问题的方式,因为这个问题只要求列出大于100MB的文件,我们可以跳过删除部分。

#! python3
# delete_files.py - Don't get misled by the program name, hah. This program
# lists the files in a folder tree larger than 100MB and prints them to the screen.
import os
folder = os.path.abspath(input('Please enter folder to search for files larger than 100MB:n'))
if os.path.isdir(folder) is True:
    i = 0  # Placeholder for number of files found larger than 100MB
    for foldername, subfolders, filenames in os.walk(folder):
        for file in filenames:
            abs_path = os.path.abspath(foldername)
            full_path = os.path.join(foldername, file)
            file_size = os.path.getsize(full_path)
            if file_size > 100000000:
                i += 1
                print(full_path)
    print(f'{i} files found larger than 100MB')
else:
    print('Folder does not exist.')

最新更新