python如何在目录中打印文件名并说不存在?

时间:2018-09-16 01:29:27

标签: python random directory operating-system

我的程序应该获得一个目录并删除该目录中的所有文件。但是,它说找不到文件(它们不存在)。我已经包含了完整的代码(因为它根本不长)和错误输出

错误输出:

  

错误404:找不到CHESS_BASE_PLAYER.3dm!
  错误404:找不到dirty-metal-texture_1048-4784.jpg!
  错误404:找不到brushed_brass ___ seamless_texture_by_rls0812-d8wzhzn.jpg!
  错误404:找不到花木侵蚀的划痕金属质感背景03.jpg!
  错误404:找不到花木侵蚀的划痕金属质感背景03.jpg!

^其中一些是文件名

代码:

import os
import random

i = 0

while i < 5: #this was just to test, not going to be included
  file = random.choice(os.listdir("C:\\Users\\t\\Desktop\\test_delete")) #change dir name to whatever
  if os.path.exists(file):
    os.remove(file)
  else:
    print("Error404: " + file + " not found!")
    pass
    i += 1

print(file)

谢谢!

0 个答案:

没有答案