-1

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
LewisJS4
  • 11
  • 1
  • 3
  • You haven't shown us what `path` is, but it sounds like you're trying to remove `folderfile` instead of `folder/file`. – user2357112 Feb 13 '18 at 02:52
  • Are there other threads or processes creating these files as you work? Is `file_list` being mutated at any point? Is this an NFS file system, or otherwise something non-local with weird behaviors? Is antivirus running? – ShadowRanger Feb 13 '18 at 02:57
  • A [mcve] with the shortest possible code that someone else can use to see the same problem would do a lot of good here. If you don't need `time.sleep()`, don't sleep. If you don't need `os.listdir()` to create the problem, don't use it. (If you *think* you need `os.listdir()` to create the problem, then your real problem is probably with how you're creating the name, not how you're deleting it, so it's probably time to add some more logging to track down the details). – Charles Duffy Feb 13 '18 at 03:46
  • @ShadowRanger Good thoughts. No other threads running. Everything is still serial. file_list is constant from the beginning of the script. – LewisJS4 Feb 13 '18 at 03:48

1 Answers1

2

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