python异常,windows错误:[错误2] 系统找不到指定的文件:“blabla.pyc”
我遇到一个问题
我正在尝试创建一个可以删除pyc文件的程序。问题是每次我通过命令行运行这个程序时,总会出现这样的消息:
windows错误:[错误2] 系统找不到指定的文件:“blabla.pyc”
这是我的代码:
directory = "C:\\Documents and Settings\\baba\\My Documents"
try:
for root, dirs, files in os.walk(directory):
for file in fnmatch.filter(files, p):
print "mencari... ",root
size = os.path.getsize(file)
dateTime = time.ctime(os.path.getmtime(file))
dateTuple = time.localtime(os.path.getmtime(file))
dateFile = dateTuple[0:3]
todayTuple = time.localtime(time.time())
todayFile = todayTuple[0:3]
if size == 0:
print "\n\n\t File name %s size %d bytes \n" %(file, size)
choice()
我知道,很多人都问过这个问题。但是,每次我尝试时,都没有人能解决。
哦,每次我把大小变量的注释放到下面,程序就能顺利运行。但是,当我不注释时,问题又出现了。
我的逻辑一定有什么问题。有没有人能给我点建议?我真的不知道该怎么办了。
谢谢你的回答
1 个回答
2
大概是猜测:
试着把 file
替换成 os.path.join(root, file)
:
absfile = os.path.join(root, file)
size = os.path.getsize(absfile)
dateTime = time.ctime(os.path.getmtime(absfile))
dateTuple = time.localtime(os.path.getmtime(absfile))
os.walk
返回的 files
是一个文件名的列表,而不是完整的路径:比如说,它可能返回 "blabla.pyc"
,但你需要的是 "C:\\Documents and Settings\\baba\\My Documents\blabla.pyc"
这样的完整路径。
所以,如果你不是在这个 directory
目录下运行这个脚本,像 getmtime
这样的函数就会出错。