Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to remove files as follows:

path = "username/hw/01/"
file_list = ["main.cc", "makefile"]
files = os.listdir(path)
del_files = list(set(files) - set(file_list))
for del_file in del_files:
  try:
    os.remove(path + del_file)
  except FileNotFoundError as e:
    print("	" + e.strerror)
  except OSError as e:
    print("	" + e.strerror)

Which is not working. If I try running

....
try:
  os.remove(path + del_file)
  os.remove(path + del_file)
except ...

the exception fires. However, if checked after with ls or nautilus, for example, the files are still there.

What works is

files = os.listdir(path)
del_files = list(set(files) - set(file_list))
while (del_files):
  for del_file in del_files:
    try:
      os.remove(path + del_file)
      time.sleep(0.5)
      print("		Removing " + path + del_file)
    except FileNotFoundError as e:
      print("	" + e.strerror)
    except OSError as e:
      print("	" + e.strerror)
  files = os.listdir(path)
  del_files = list(set(files) - set(file_list))

This is incredibly ugly. When print statements are included, it will run more than once to get all of the requested files. What am I missing?

If it matters,

$ python3 --version
Python 3.4.3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

You might need to use os.remove(os.path.join(path, del_file)) instead of os.remove(path + del_file) if path doesn't end with a path separator. Docs: os.path.join()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...