OSX Hidden File Cleanup

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

OSX Hidden File Cleanup

Post by devnull » Sun Apr 07, 2019 2:20 am

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 !

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: OSX Hidden File Cleanup

Post by stijn » Sun Apr 07, 2019 7:02 am

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

User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

Re: OSX Hidden File Cleanup

Post by devnull » Sun Apr 07, 2019 9:29 am

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

stijn
Posts: 735
Joined: Thu Apr 24, 2014 9:13 am

Re: OSX Hidden File Cleanup

Post by stijn » Sun Apr 07, 2019 10:33 am

No, good point, it's in micropython-lib

Post Reply