请不要标记为重复,因为我已经查看了此错误的其他问题,我仍然无法弄明白。
我正在制作一个扫描给定目录的基本扫描程序,它会删除超过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
。有人可以帮忙吗?任何帮助都受到广泛赞赏。
答案 0 :(得分:1)
os.walk
返回3元组(dirpath, dirnames, filenames)
。您当前的方法在3元组上进行迭代,在第二次迭代中,它会给出目录名称列表dirnames
。
但是,您只对dirnames
:
for _, dirs, _ in os.walk(path):
for folder in dirs:
...
答案 1 :(得分:0)
适合我:
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: