1. Home
  2. Computing & Technology
  3. Python

Part 2: Getting Feed Information From the Data File With Python

From Al Lukaszewski, for About.com

6 of 9

Defining the First Python Function

In defining functions, it is always best to give them a name that describes their function. While you could name your functions after tropical fruit and Python would not care (as long as you did so consistently), it is not best practice. It is also bound to get you in trouble with anyone who must read your code after you have written it. At the very least, they will question your sanity. Python code is pretty hard to obscure, but that is a good way to do it.

So, for our RSS Reader, the function that returns the feed list information will be called 'getlistinfo' because that is what it does. Here is the beginning of the function:

def getlistinfo(type):
     filename = "feedlist." + type
     datafile = open(filename, "r")
We will add to this as we progress, but we start with three lines for the sake of space.

In the definition declaration, we tell Python that the function requires one argument which, in the function, is called type. The next line gives context for what type is. We concatenate the string 'feedlist.' with the suffix type in order to get the name of the file, filename.

Why, you may ask, do we not just hardwire the name of the file into the code? Doing so would restrict us in later development. Since type can be any string, the suffix of 'feedlist.' can be anything as well. Therefore, we can re-use this function in a later tutorial when we implement images and other goodies in our RSSReader.

Next, we pass the name to Python's built-in open command and create a file object, datafile. While using the 'r' flag is not necessary, it is a good habit to have. Now that we have a file object, we are ready to read from it.

If any of this seems out of your depth, not to worry. Consult my tutorial on file input and output and then come back.

About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >