Page 1 of 1

OSX Hidden File Cleanup

Posted: Sun Apr 07, 2019 2:20 am
by devnull
Thought I would share this which is only really applicable where the device is mounted in the OSX filesystem (i.e. pyboards)

osxcln.py

Code: Select all

import os
 
def deltree(target):
  print("deltree", target)
  try:
    for d in os.listdir(target):
      try:
        deltree(target + '/' + d)
      except OSError:
        os.remove(target + '/' + d)
    os.rmdir(target)
  except:
    pass

def run():
  for file in os.listdir():
    if file.startswith('._'):
      os.remove(file)
      print(file,'deleted')

  deltree('.fseventsd')
  deltree('.Trashes')
  deltree('.TemporaryItems')

  print('\n============')
  print("\n".join(os.listdir()))

run()
Thanks to mitch: https://stackoverflow.com/a/53141102/588504

Any suggestions or improvements welcome !

Re: OSX Hidden File Cleanup

Posted: Sun Apr 07, 2019 7:02 am
by stijn
If this went under full review here, purely on the code (have no OSX anymore so cannot really comment on functionality but it does seem to do what it's supposed to):
- deal with errors: you're printing when deltree starts, but when something goes wrong nothing is printed so that output is kinda useless. That 'pass' in the except block should actually do something. In run() on the other hand, you are printing when something gets deleted, but there's no error handling.
- use os.path.join instead of manually concatenating paths, avoid duplication and use a variable to hold the concatenated path
- 'run' is a super generic name, could be better. But definitely add an argument so the user can choose the directry to run in, relying on working directory is a mess. If you really want it you can still default the argument to '.'
- eventually merge loop/filter like for (file for file in os.listdir() if file.startswith('._')):, that's one less indent level for the loop
- fix inconsistencies in whitespace and use of quotes for strings

Re: OSX Hidden File Cleanup

Posted: Sun Apr 07, 2019 9:29 am
by devnull
Thanks for all the suggestions for improvements, but this is executed from the pyboard device REPL, not on the OSX operating system itself.

I don't think micropython's os has path.join() ??

Re: OSX Hidden File Cleanup

Posted: Sun Apr 07, 2019 10:33 am
by stijn
No, good point, it's in micropython-lib