File System Storage ------------------- Sometimes you need to store useful information. This information is stored as data: the representation of information (in numeric form when stored on a computer). If you store data on a computer, it should be retained even if you turn the device off and on again. MicroPython allows you to do this using a very simple file system. What is a file system? It is a way of storing and organizing data in a persistent manner - any data stored in the file system should continue to exist after the device restarts. As the name implies, data stored in the file system is organized into files. .. image:: /_static/products/ledong-v2/_static/image/tutorials/files.jpg A computer file is a named digital resource stored on a file system. These resources contain useful information as data. This is exactly how paper files work. It is a named container that holds useful information. Usually, both paper and digital files are named to indicate what they contain. On a computer, a file usually ends with a ``.xxx`` suffix. Usually it indicates what type of data is used to represent the information. For example, ``.txt`` indicates a text file, ``.jpg`` a JPEG image, and ``.mp3`` sound data encoded as MP3. Some file systems (such as those on a laptop or PC) allow you to organize files into directories: named containers that group related files and subdirectories together. However, the file system provided by MicroPython is a flat file system. A flat file system has no directories - all files are just stored in the same place. The Python programming language contains easy-to-use and powerful ways to work with a computer's file system. MicroPython on mPython implements a useful subset of these features, making it easy to read and write files on the device, while also providing consistency with other versions of Python. Opening Files +++++++++++++ The following is a description of the relevant operations for Python File operations. The open() method:: #open(path + filename, read/write mode), e.g. f=open('/tmp/hello','w') #Read/write modes: r read-only, r+ read/write, w new (overwrites the existing file), a append, b binary file. e.g. 'rb','wb','r+b' and so on The types of read/write modes are: rU or Ua open for reading, also provides universal newline support (PEP 278) w open for writing, a open for appending (starting at EOF, creating a new file if necessary) r+ open for reading and writing w+ open for reading and writing (see w) a+ open for reading and writing (see a) rb open in binary read mode wb open in binary write mode (see w) ab open in binary append mode (see a) rb+ open in binary read/write mode (see r+) wb+ open in binary read/write mode (see w+) ab+ open in binary read/write mode (see a+) A file object is created using the open function. The table below lists the commonly used functions of a file object:: file.read([size]) #If size is not specified, returns the entire file; there is a problem if the file size is more than twice the memory. f.read() returns "" (empty string) when it reads to the end of the file file.readline() #Returns one line file.readline([size]) #Returns a list containing size lines; if size is not specified, returns all lines for line in f: print line #Access via an iterator file.write("hello\n") #If you want to write data other than a string, first convert it to a string. file.tell() #Returns an integer representing the current position of the file pointer (i.e. the number of bytes from the file header). file.seek(offset,[starting position]) #Used to move the file pointer. offset: unit: bytes, can be positive or negative; starting position: 0-file header, default value; 1-current position; 2-file end. file.close() #Close the file For more usage of open(), see the :term:`CPython` documentation:`open() `_. ------------------------------------------------------------------------------------------------------------------------- Reading and writing files on the file system is implemented through the ``open`` function. After opening a file, you can use it until you close it (similar to how we use paper files). The best way to ensure this is to use a with statement as follows:: with open('story.txt') as my_file: content = my_file.read() print(content) The ``with`` statement uses the ``open`` function to open a file and assign it to an object. In the example above, the ``open`` function opens the file called ``story.txt`` (obviously a text file containing some kind of story). The object used to represent the file in Python code is called ``my_file``. Then, in the code block indented below the ``with`` statement, the ``my_file`` object is used to ``read()`` the content of the file and assign it to the ``content`` object. Here is an important point: the next line containing the ``print`` statement is not indented. The code block associated with the ``with`` statement is just the single line that reads the file. Once the code block associated with the ``with`` statement closes, Python (and MicroPython) will automatically close the file for you. This is called context handling, and the object created by the ``open`` function is the file's context handler. In short, the scope of interacting with the file is defined by the code block associated with the with statement that opens the file. Confused? Don't be. I'm just saying your code should look like this:: with open('some_file') as some_object: # Complete the reading and writing of the file in this code block # When the block is complete, MicroPython then # automatically closes the file for you. Just like paper files, there are two reasons to open a file: to read its content (as shown above) or to write content to the file. The default mode is to read the file. If you want to write to the file, you need to tell the ``open`` function as follows:: with open('hello.txt', 'w') as my_file: my_file.write("Hello, World!") Note that the ``'w'`` parameter is used to set the ``my_file`` object to write mode. You can also pass an ``'r'`` parameter to set the file object to read mode, but since this is the default setting, it is usually left out. Writing data to a file is done through (you guessed it) the ``write`` method, which takes the string you want to write to the file as a parameter. In the example above, I wrote the text "Hello, World!" into a file named "hello.txt". .. note:: * When you open a file and write to it (possibly multiple times while the file is open), if the file already exists, you will overwrite the file content. * If you want to append data to a file, you should first read it, store the content somewhere, close it, append the data to the content, and then open it to write again with the modified content. OS ++++++ In addition to reading and writing files, Python can also manipulate them. You certainly need to know the files in the file system, and sometimes you also need to delete them. On a regular computer, the role of the operating system (such as Windows, OSX or Linux) is to manage this on behalf of Python. In Python, such functionality is provided through a module called os. Since MicroPython is the operating system, we decided to keep the appropriate functionality in the os module for consistency, so that when you use "regular" Python on a laptop or a device like a Raspberry Pi, you know where to find them. Basically, you can perform three operations related to the file system: list files, delete a file, and query the size of a file. To list the files on the file system, use the listdir function. It returns a list of strings indicating the filenames of the files on the file system:: import os my_files = os.listdir() To delete a file, use the remove function. It takes a string representing the filename of the file to delete as a parameter, as shown below:: import os os.remove('filename.txt') Commonly used os methods:: os.chdir(path) #Change the path os.getcwd() #Get the current path os.listdir(dir) #Directory listing os.mkdir(dir) #Create a directory os.remove(path) #Delete a file os.rmdir(dir) #Delete a directory os.rename(old_path, new_path) #Rename a file os.stat(path) #File/directory status, explained in detail below: For more usage of the os module, see the :mod:`os` module chapter. The Main Program main.py ++++++++++++++++++++++++ boot.py and main.py are two files specially handled by MicroPython at startup. First the boot.py script is executed (if it exists), and then the main.py script is executed after it completes. In addition, if you copy other Python files onto the file system, then import works just like any other Python module. For example, if you have a ``hello.py`` file containing the following simple code:: def say_hello(name="World"): return "Hello, {}!".format(name) You can import and use the ``say_hello`` function like this:: from mpython import * from hello import say_hello print(say_hello()) .. note:: If a script has been flashed onto the device in addition to the MicroPython runtime, then MicroPython will ignore main.py and run your embedded script. To flash only the MicroPython runtime, just make sure the script you write in the editor contains zero characters. Once flashed, you can copy the main.py file. .. footer:: The image of paper files is used under a Creative Commons License and is available here: https://www.flickr.com/photos/jenkim/2270085025