Skip to main content

Files in python

Files in python


Python allows us to store our code in files (also called modules). This is very useful for more
serious programming, where we do not want to retype a long function definition from the very
beginning just to change one mistake. In doing this, we are essentially defining our own modules,
just like the modules defined already in the Python library. For example, to store our squaring
function example in a file, we can use any text editor 3 to type the code into a file, such as
def square ( x ):
return x * x
Notice that we omit the prompt symbols >>>, ... when typing the code into a file, but the
indentation is still important. Let’s save this file under the name “SquaringFunction.py” and then
open a terminal in order to run it:
d o t y @ b r a u e r :~% python
Python 2.5.2 ( r252 :60911 , Apr 21 2008 , 1 1 : 1 2 : 4 2 )
[ GCC 4.2.3 ( Ubuntu 4.2.3 -2 u b u n t u 7 )] on linux2
Type " help " , " c o p y r i g h t" , " c r e d i t s" or " l i c e n s e"
for more i n f o r m a t i o n .
>>> from S q u a r i n g F u n c t i o n import square
>>> square (1.5)
2.25
Notice that I had to import the function from the file before I could use it. Importing a command
from a file works exactly the same as for library modules. (In fact, some people refer to Python
files as “modules” because of this analogy.) Also notice that the file’s extension (.py) is omitted
in the import command.

Comments