How to use a USB Flash drive in Python
From Digi Developer
Contents |
How to access an Attached USB Flash drive in Python
This article is about using the Attached USB Flash drive in Python, methods of reading and writing to it, and the current limitations of such.
See this Wiki page for information on FLASH filesystem statistics: Estimating_Free_Flash_File_Space
Hardware Requirements
- A Digi USB/Python Enabled device. Typically a ConnectPort X4 or ConnectPort X8 device.
- A Compatible USB flash drive. Most flash drives are compatible. To check, see 'Detecting your USB flash drive' section below.
- Command line interface access to the Digi device.
Detecting your USB flash drive
To detect your USB flash drive, attach the USB drive to an external USB port of the Digi device. Connect to the command line interface of the device, and type the command flashdrv. If a USB drive is detected, it will display volume information such as: The name of the USB flash drive, total space, used space, available space, and which volume it is mounted as. Make note of which volume the device is mounted as, typically A. Drive volume letters are assigned starting with A and progressing sequentially through the alphabet. It is not recommended that more than one drive be used, without an additional mechanism to identify the volume label, because the enumeration process may assign different letters on boot in this case.
Writing and reading to your USB flash drive
To write and read from the USB flash drive, the volume the drive is mounted at is needed. For the example below, we will be assuming your drive is mounted as A.
fh = open("A/tmp.file", 'w') fh.write("Foobar") fh.close() fh = open("A/tmp.file", 'r') print (fh.read())
The above code opens a file on the volume mounted at A, writes to it, closes it, then reopens it and reads back the data within. If the file does not exist, the file will be created. The write method is destructive and will overwrite existing data. Use the append method below if needed.
fh = open("A/tmp.file", 'a') fh.write("Foobar 2") fh.close() fh = open("A/tmp.file", 'r') print (fh.read())
The above code opens a file on the volume mounted at A, appends it, closes it, then reopens it and reads back the data within. Data by default appended sequentially. If a carriage return is desired use "\n".
Limitations of the USB flash drive
Similar to built in flash of the Digi product, the supported python os commands are listed in the Digi Python Programming guide. In addition to that, there is no way currently in the web user interface and command line interface to list the contents either.
To test whether or not a file exists, you must attempt to open it. The exception that is generated will show you whether or not the file exists. If the file does not exist, an "IOError: [Errno 13] Permission Denied" exception will be generated.
