扫描文件夹时出现各种错误

Various errors while scanning for folders

请不要标记为重复,因为我已经查看了其他有此错误的问题,但我仍然无法弄清楚。

我正在制作一个基本的扫描器,它可以扫描给定的目录并删除所有超过 90 天的子目录。这是代码:

import os, sys
import time
import shutil
from  Tkinter import *
import Tkinter, Tkconstants, tkFileDialog



now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for x in os.walk(path):
    for folders in x:
        while os.stat(folders).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days' 

这是完整的回溯:

Traceback (most recent call last):
File "C:/Users/Bill/Desktop/limitScanner/scanner.py", line 20, in <module>
while os.stat(folders).st_mtime < now - 90 * 86400:
TypeError: coercing to Unicode: need string or buffer, list found

编辑:当我在具有多个子文件夹(例如桌面文件夹)的文件夹上使用我的程序时,出现以下错误:WindowsError: [Error 2] The system cannot find the file specified 和第一个文件夹的名称。

我正在使用 python 2.7.13。有人可以帮忙吗?非常感谢任何帮助。

os.walk returns 三元组 (dirpath, dirnames, filenames)。您当前的方法迭代 3 元组,在第二次迭代中给出目录名称列表 dirnames.

但是,您只对 dirnames:

感兴趣
for _, dirs, _ in os.walk(path):
    for folder in dirs:
        ...

适合我:

import os, sys
import time
import shutil
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

now = time.time()
home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to scan from: ")
path = path.encode('utf-8')

for _, x ,_ in os.walk(path):
    for folders in x:
        if os.stat(os.path.join(path,folders)).st_mtime < now - 90 * 86400:
            q = raw_input('Folder(s) found. NOTE: This will delete all directories or subdirectories in the folder. Do you want to remove?(y/n) ')
            if str(q) == "y" or str(q) == "Y":
                shutil.rmtree(path, ignore_errors=True)
                print 'Successfully deleted folder(s)'
            elif str(q) == "n" or str(q) == "N":
                print 'Folders not deleted.'
                sys.exit()
        else:
            print 'No folder(s) over 90 days'

我按照 Moses 所说调整了 os.walk(path) 输出,将 while 更改为 if 并添加了 (os.path.join(path,folders),因此 os.stat(...) 可以在问题。

for _, x ,_ in os.walk(path):
    for folders in x:
        if os.stat(os.path.join(path,folders)).st_mtime < now - 90 * 86400: