Python Language Tutorial Part- 4

Today I will take a new part of python from my tutorial series. In this part you will learn the usage of Module and I/O. Both concept are known in every language.

I already told you the following:

Download Python Language Tutorials and give star on GitHub if that files are helpful for you.

In this article you will understand the following:

  • Module
  • Input and Output (I/O)

Module

If you want to write a longer program, then you can use file as input. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a function that you’ve written in several programs without copying its definition into each program.

Python has a way to put definitions in a file and use them in a script. Such a file is called a module; definitions from a module can be imported into other modules or into the main module. A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

  1. def fun1(n): # write Fibonacci series up to n  
  2. a, b = 01  
  3. while b < n:  
  4. print(b, end=' ')  
  5. a, b = b, a+b  
  6. print(a)  
  7. def fun2(n): # return Fibonacci series up to n  
  8. result = []  
  9. a, b = 01  
  10. while b < n:  
  11. result.append(b)  
  12. a, b = b, a+b  
  13. return result  
  14.               
In this example, above code save into any file name with extension .py. I save this file with fun.py name.

After that again create new Python file and add import fun where fun is python file name.

After that call that function which you want to use.

Example 1: Using the module name you can access the functions:
  1. #!/usr/bin/python  
  2. # -*- coding: utf-8 -*-  
  3. import fun  
  4. fun.fun1(1000)  # it call first method from fun.py file  
  5. val = fun.fun2(100)  # it call second method from fun.py file  
  6. print val  
  7. print fun  # it show location of modula/file  
  8. print fun.__name__  # it print the file name  
  9. fib = fun.fun1  
  10. fib(500)  
  11. print dir(fun)  
  12.   
  13.               
Output:

 

    1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 987
    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    <module 'fun' from 'C:\\Users\\NeErAj\\Projects\\demo\\fun.py'>
    Fun
    1 1 2 3 5 8 13 21 34 55 89 144 233 377 377
    ['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', 'fun1', 'fun2']

Example 2: import statement that imports names from a module directly into the importing module:

  1. from fun import fun1,fun2  
  2. fun1(500)  
  3. val=fun2(500)  
  4. print(val)  
Output:

 

    1 1 2 3 5 8 13 21 34 55 89 144 233 377 377
    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Input & Output

There are several ways to present the output of a program through which data can be printed in a human-readable form.

Output Formatting:

Example 1:

  1. #!/usr/bin/python  
  2. # -*- coding: utf-8 -*-  
  3. s = 'Hello, world.'  
  4. print str(s)  
  5. print repr(s)  
  6. print str(1 / 7)  
  7. x = 10 * 20  
  8. y = 200 * 300  
  9. s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'  
  10. print s  
  11.   
  12. # The repr() of a string adds string quotes and backslashes:  
  13.   
  14. hello = 'hello, world\n'  
  15. hellos = repr(hello)  
  16. print hellos  
  17.   
  18. # The argument to repr() may be any Python object:  
  19.   
  20. print repr((x, y, ('spam''eggs')))  
  21.   
  22.               
Output:

 

    Hello, world.
    'Hello, world.'
    0.14285714285714285
    The value of x is 200, and y is 60000...
    'hello, world\n'
    (200, 60000, ('spam', 'eggs'))

Example 2:

  1. for x in range(111):  
  2. print(repr(x).rjust(2), repr(x*x).rjust(3), end=' '#rjust() = Right Justify  
  3. # Note use of 'end' on previous line  
  4. print(repr(x*x*x).rjust(4))  
  5. for x in range(111):  
  6. print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))  
Output:

 

    1 1 1
    2 4 8
    3 9 27
    4 16 64
    5 25 125
    6 36 216
    7 49 343
    8 64 512
    9 81 729
    10 100 1000
    1 1 1
    2 4 8
    3 9 27
    4 16 64
    5 25 125
    6 36 216
    7 49 343
    8 64 512
    9 81 729
    10 100 1000

Example 3:

  1. table = {'Alwar''0144' , 'Jaipur''0141' , 'Ajmer''0142' }  
  2. for city, pincode in table.items():  
  3. print('{0:5} ==> {1:5}'.format(city, pincode))  
Output:

 

    Ajmer ==> 0142
    Jaipur ==> 0141
    Alwar ==> 0144

Reading and Writing Files

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

  1. f = open('workfile''w')  
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. Mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it is omitted.

Methods of File Objects

Example:
  1. f = open('file''wb+')  
  2. f.write(b'0123456789abcdef'#It write text into file  
  3. f.seek(5# Go to the 6th byte in the file   
  4. print(f.read(1))  
  5. f.seek(-32# Go to the 3rd byte before the end  
  6. print(f.read(1))  
Output:

 

    b'5'
    b'd'

Example:

  1. with open('workfile''r') as f:  
  2. read_data = f.read()  
  3. f.closed  
  4. print(read_data)  
Output:

 

    0123456789abcdef

File objects have some additional methods such as isatty() and truncate() which are less frequently used.

I hope you will understand this part of python programming language.

Up Next
    Ebook Download
    View all
    Learn
    View all