Sep 1, 2010

Python modules

We can create a module file and can use it in some other files. TO do that we must create the module file in the same directory and in our coding we must import it. If the module file is "module_file.py".
>>>import module_file
Then we can get the variables and methods by;
>>>module_file.variable #or
>>>module_file.method

We can view the thing in a module by doing
>>>import module
>>>def(module)
This will give all related details about the module.

Inputs and outputs
We can pass parameters when we are executing the python script.
$python script.py argument1 argument2

in the script we can use these arguments by using
if __name__="__main__":
import sys
function(sys.arg[1], sys.arg[2])

Open file
we can use this to open a externel file.
f=open('file_name','mode')
mode can be,
w - write
r - read
r+ - read and write
a - append

f.read(size) - will give the size
f.read - will read the file
f.readline - will read a line
f.write(string) - will write string to file
f.close() - will close the file

Format an output
for x in range(1,11)
print repr(x).rjust(2), repr(x*x).rjust(3),
repr(x*x*x).rjust(4)

this will give the output like this
1 1 1
2 4 8
3 9 27
4 16 64 ....

No comments:

Post a Comment

Your comments are always welcome ...