Part 3: Get started with Python: Functions and File Handling

This is a tutorial series which will teach you how to code in Python. We will start with the absolute basics of installation of Python in Windows and Python Tools in Visual Studio. We will then go through basic constructs in Python and write a couple of programs to summarize what we have learned. We will end with an Object Oriented Approach using Python and a specific feature of Python Tools in Visual Studio: Mixed mode C/C++/Python Debugging

Part 1: Get Started with Python summarized the steps involved to setup Python and Visual Studio for Python Development. We essentially learned how to install Python in Windows, Visual Studio and Python Tools for Visual Studio.

Part 2: Get Started with Python took you through the basics in programming constructs such as output, input, variables and control flow statements including conditional statements and loops including while and for. Using these tools was enough to get started with coding basic applications in Python.

Part 4: Get started with Python: Object Oriented Approach




Part 5: Get started with Python: Debugging in PTVS

Part 6: Get started with Python: Build your first Django Application in PTVS

Part 3: Functions and File Handling

Welcome to this weeks edition of Get Started with Python! In this section, let us take a deeper dive. We will be looking into Functions and File Handling. After having gone through this, we will develop an application using Functions and Files to demonstrate the ease of use and utility of these constructs.

Function Handling

Functions are blocks of code which are logically grouped to perform some action. In Python, a function is defined using the ‘def’ keyword, followed by the name of the function, followed by the list of parameters in parenthesis, followed by ‘:’. The distinctive feature in Python being that the block of code is not delimited by brackets or parenthesis, but by an indentation of a tab space. The first line is an optional line in quotes which is called as a ‘docstring’ and can be used by third party tools for documentation purposes. The code snippet below gives a brief description of the syntax and the usage.

 1: def <function_name> (<parameter list>):
 2:     "<docstring>"
 3:     ...
 4:     ...

File Handling

As most other procedural languages, the most important object in File handling is the File Object handler, the difference being that there is no need to import or include any additional libraries. We get the file object handler using the ‘open’ construct. The file can be opened in either read, write or append mode. We use the ‘write’ construct to write contents in the file while we use the ‘read’ construct to read contents from the file. After we finish our operations with the file, we close the file using the ‘close’ construct. The following code snippet shows the syntax and the usage.

 1: FileHandle=open("<file_name>",'<mode>')        #file_name is the name of the file
 2:                                                #<mode> is either r, w, a
 3: FileHandle.write("<text>\n")                   #<text> will be the content of the file
 4:                              #reads the content of the file
 5: FileHandle.readline()                          #reads the content line by line
 6: FileHandle.close()                             #closes the file



ReadTextMessage Application

Now that we have gone through function and file handling, let us look into how both of these can be used to build an application. We will first define the objective of the application, explain the design which will be followed by the code.


Expand regularly used short-forms in text message jargon. For eg: lol, rofl and lmao will be expanded to “laughing out loud”, “rolling on the floor laughing” and “laughing my a** out” respectively.


  • def mainfunction() : This will make the call to all the other functions
  • def filewrite(): This will write contents to the file
  • def filecheck(): Will open and check the validity of the existence of the file
  • def separatewordlist(): separate the contents of the file into words
  • def dictionarylist(): creates 2 lists, one containing the words and the other contains the expansion
  • def compare(): compare the final list of words
  • def printMessage(): prints the final message

Find the details of the code of the app:

 1: #This is the main function
 2: def mainFunction():
 3:     print("Please enter the message (no punctuations please):")
 4:     message = input(">") #will asign message with the user's message
 5:     fileWrite(message) #will write the to a file
 6:     fileCheck("TextFile2.txt") #will check if the file exists or not
 7:     messageWords = seperateWordsList("TextFile1.txt") #will create a list of all words in the message
 8:     AllWords, AllDefs = dictionaryList("TextFile2.txt") #will create two lists - one containing the words, the other containing the definitions
 9:     finalWords = compare(messageWords, AllWords, AllDefs) # the final list of words for the message
 10:     printMessage(finalWords) #will print the message
 12: #This will write the message to a file
 13: def fileWrite(message):
 14:     fileObj = open("TextFile1.txt","w") #creates the file object with the name "TextFile1.txt"
 15:     fileObj.write(message) #writes a message to the file
 16:     fileObj.close() #closes the file objects
 18: #will check if the file exists or not
 19: def fileCheck(fileName):
 20:     try:
 21:         fileObj = open(fileName) #will try to open the file
 22:     except IOError: #will handle the exception
 23:         print("The file could not be opened.")
 24:         print("Either the file does not exist, or you have entered the wrong name.")
 25:         os.system("pause")
 26:         os.system("cls")
 27:         mainFunction()
 29: #will seperate words and return a list of words
 30: def seperateWordsList(fileName):
 31:     fileObj = open(fileName)
 32:     fileContents =
 33:     AllWords = fileContents.split() #will split the entire file contents into words 
 34:     return AllWords
 36: #This function is to return two lists - one containing all the short forms, the other containing the definitions
 37: def dictionaryList(fileName):
 38:     fileObj = open(fileName)
 39:     AllWords = []
 40:     AllDefs = []
 41:     for line in iter(fileObj): #This for loop will read the file line by line
 42:         words = line.split() #This will split the sentence into a list of words
 43:         AllWords.append(words[0]) #appends the short form to this list
 44:         s = ""
 45:         for x in range(2,len(words)):
 46:             s = s + words[x] + " " 
 47:         AllDefs.append(s[0:len(s) - 1]) #appends the definition to this list
 48:     return (AllWords, AllDefs)
 50: #this function will compare message words and those in dictionary
 51: def compare(messageWords, AllWords, AllDefs):
 52:     for x in range(0, len(messageWords)):
 53:         word = messageWords[x]
 54:         for y in range(0, len(AllWords)):
 55:             if(word.upper() == AllWords[y]): 
 56:                 messageWords[x] = AllDefs[y] #This will replace the word with the dictonary definition if it's true
 57:     return (messageWords)
 59: #will print the message based on the list finalWords
 60: def printMessage(finalWords):
 61:     message = ""
 62:     for word in finalWords: 
 63:         message = message + " " + word
 64:     print(message[1:]) #will remove the inital space
 66: mainFunction()

The output of this application on execution looks as follows:




Understanding and using files and functions is key to the development for any  application. Now you are definitely equipped with enough arrows in your quiver to start developing your applications on Python. In the next part, I will cover an object oriented approach to programming in Python which will include classes and objects. So stay tuned and hope to see you there !

Comments (0)

Skip to main content