title: Copy file to USB automatically on mount Raspberry Pi
body: <p>I'm currently doing a project which requires a file to be automatically copied to USB-stick on mount. Based on my research in internet, I believe it is doable using udev rule. So, when an USB is inserted into my RPi2, the udev rule will then execute a python script which allows file to be copied to the USB-stick.</p>
  
  <p>Problem is, I also heard that the script will be executed before the RPi mount the USB, which means the file will not be copied. Is there a solution to this? The python script was executed when i copied the file internally (on RPi itself not USB), it just doesn't work when I tried to copy it to USB.</p>
  
  <p>Below are my code:</p>
  
  <p>Udev rule</p>
  
  <pre><code>KERNEL=="sd*1", ACTION=="add", RUN=="/home/pi/datalogger/autocopy.sh"
  </code></pre>
  
  <p>Shell script</p>
  
  <pre><code>cd /
  cd /home/pi/datalogger
  sudo /usr/bin/python autocopy.py
  cd / 
  exit
  </code></pre>
  
  <p>Python script</p>
  
  <pre><code>import shutil
  import datetime
  
  # File to be copied
  source = "/home/pi/copied.txt"
  
  # USB name must be changed to 'USB1' in order for auto copy to work
  destination = "/media/pi/USB1/datalogger_backup_%s.txt" % datetime.datetime.now().date()
  
  try:
     # Copy file to destination
     shutil.copy2(source, destination)
     # E.g. source and destination is the same location
  except shutil.Error as e:
     print("Error: %s" % e)
     # E.g. source or destination does not exist
  except IOError as e:
     print("Error: %s" % e.strerror)
  </code></pre>