想自己写一个遍历系统文件,删除大文件的脚本。在网上找了个模板,自己做了一些修改
import os import sys rootname1 = r"c:/" def findlargefile(a): #用os.walk来遍历,网上可以查到很多资料 for parent,dirnames,filenames in os.walk(rootname1): for filename in filenames: #获取文件的绝对路径,用getsize取得文件大小 currentPath = os.path.join(parent,filename) filesize = os.path.getsize(currentPath)/1024/1024 #文件大于50M则打印路径 if filesize > 50: print currentPath findlargefile(rootname1) raw_input('enter')
然而执行过程中,被一个winerror错误中断了
Traceback (most recent call last):
File "C:\Users\lzhan111\Desktop\import os.py", line 25, in <module>
findlargefile(rootname1)
File "C:\Users\lzhan111\Desktop\import os.py", line 16, in findlargefile
filesize = os.path.getsize(currentPath)/1024/1024
File "D:\Python27\lib\genericpath.py", line 57, in getsize
return os.stat(filename).st_size
WindowsError: [Error 3] The system cannot find the path specified: 'c:/Documents and Settings\\lzhan111\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\Low\\Content.IE5\\4MF7JJ1X\\css__GuHIA0MRerv9mrukwwBMrtZewTvJBiWHQRjRsHtTbAE__ZftjpDRUF6KWTGC_hUDhloDg47KlEj6eruPcpcw_RF8__oq5F0nNPXAaJI-M35d2JEXbyaYY0bdWSyLcibKOOmOo[1].css'
File "C:\Users\lzhan111\Desktop\import os.py", line 25, in <module>
findlargefile(rootname1)
File "C:\Users\lzhan111\Desktop\import os.py", line 16, in findlargefile
filesize = os.path.getsize(currentPath)/1024/1024
File "D:\Python27\lib\genericpath.py", line 57, in getsize
return os.stat(filename).st_size
WindowsError: [Error 3] The system cannot find the path specified: 'c:/Documents and Settings\\lzhan111\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\Low\\Content.IE5\\4MF7JJ1X\\css__GuHIA0MRerv9mrukwwBMrtZewTvJBiWHQRjRsHtTbAE__ZftjpDRUF6KWTGC_hUDhloDg47KlEj6eruPcpcw_RF8__oq5F0nNPXAaJI-M35d2JEXbyaYY0bdWSyLcibKOOmOo[1].css'
发现找不到文件,但去指定目录下,文件是存在的。
在网上翻了很久,都没有解决,突发奇想会不会是文件名的长度问题,事实证明文件命的长度是有影响的。把相应的文件名删减一部分就行了
不知道是不是os.path.getsize()对参数的长度有要求还是咋的,总之,有类似的问题,可以考虑换下文件名试试。
优化了一下代码,无视那些名字过长的文件0 0
import os import sys rootname1 = r"c:/" #print os.walk(dirname) def findlargefile(a): for parent,dirnames,filenames in os.walk(rootname1): for filename in filenames: currentPath = os.path.join(parent,filename) try: filesize = os.path.getsize(currentPath)/1024/1024 except: print 'badthing happen' if filesize > 50: print currentPath findlargefile(rootname1) raw_input('enter')