Python os.remove fails to remove

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("\t" + e.strerror)
  except OSError as e:
    print("\t" + 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("\t\tRemoving " + path + del_file)
    except FileNotFoundError as e:
      print("\t" + e.strerror)
    except OSError as e:
      print("\t" + 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

1 answer

  • answered 2018-02-13 02:57 Adam Schettenhelm

    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()