Education, Learning, Technology

User Defined Modules – Importing your own

Just like you import standard modules like os, csv, random etc you can import python modules written by you into other python programs.

For example if you write a package of functions inside a module and save it as mymodule.py, you would import it into another program with the below statement.

import mymodule

Now Let us consider a sample user defined module processcsv.py that has a function udf_readcsv() taking a csv file as an argument and checks if given csv file exists and reads the data from it into a list.

import csv
import os
import sys

# Check if file exists in the file path. Return empty list if no file found
# if file present then read the file and return data as a list

def udf_readcsv(fp):
    print("Calling function",sys.argv[0])
    DATA_FILE_NAME = fp
    line_list = []
    if(not os.path.exists(DATA_FILE_NAME)):
        return line_list

    fh = open(DATA_FILE_NAME, 'rU')
# Read csv file using the file handler
    csvParsed = csv.reader(fh)

    for row in csvParsed:
        line_list.append(row)
    return line_list

Now let us import this module in another python program.

import processcsv

try:
    data1=processcsv.udf_readcsv()
    print(data1)
except TypeError:
    print("Please check if you have passed the argument required")

try:
    data=processcsv.udf_readcsv('ppd_data.csv')
    print(data)
except:
    print("Error during processing")

 

That’s it. Note that there is no .py extension in the import and you are free to use the function inside the module

Just ensure that the csv file, imported module and calling code are in the same directory. If not you have to provide full paths.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s