Python Load Functions
The Python programming language has several functions that you can use to load different modules into your program. The import statement lets you bring blocks of code from other Python modules, while the reload function lets you import modules previously brought in, but which may have been modified. The open function lets you view and modify other types of files.
-
Import Statement
-
Several large computer programs break up source code into several files, called scripts or modules. Each module usually contains several related functions or classes, such as math or string functions. To use each module in the same Python program, you have to import them, either into new modules you are creating, or the main body of your program. To import a module into your program, type "import moduleName" at the top of your code.
Reload Function
-
Python's reload function works in a similar manner to the import function, although it is syntactically different. This function lets you import a module that has already been brought into your program. The advantage comes when you have a server running a Python program that you do not want to terminate, but you still want to modify a module. You can edit the script as needed, then use the reload function to bring it back into the program with the changes. Type "reload(moduleName)" to use this function.
-
Open Function
-
To open a file for editing in your Python program, use the open function. You can use it to open text documents or images. The function itself takes one required parameter and one optional parameter. First, you must provide a string, which is a path to the file you want to open. The second parameter is the mode in which you want to open it, such as read, write or append. The default is read mode. Type "file = open('path/to/file', 'a')" to open a file in append mode.
Considerations
-
It is important where you place these functions in your program. You must call them before you intend to use the results of the call. For example, if you try to use a math function from a module before actually importing the module into your program, the function will not work correctly. It is best to use the import statement as the first lines in your program or function. You should only use the reload and open functions at the point in your program where you need them.
-