The Python Docs and File Redirection

At the end of Comments and Files, I gave you the fairly trivial task of updating the ‘colours of the rainbow’ script to read its data from a file.

You could have just copied the contents of input_from_a_file.py, and it would have done the job.

I decided to rename the list though, so that the script accurately documents what data it expects from data.txt

def print_my_list(my_list):
  for item in my_list:
    print item

def main():
  with open('data.txt') as f:
    colours_of_rainbow = f.readlines()
	
  print_my_list(colours_of_rainbow)

if __name__ == '__main__':
  main()

You could have went with something more generic if you wished:

print_my_list_from_file.py:

def print_my_list(my_list):
  for item in my_list:
    print item

def main():
  with open('data.txt') as f:
    my_list = f.readlines()
	
  print_my_list(my_list)

if __name__ == '__main__':
  main()

The other thing you had to do was create a file with the data.

data.txt:

red
orange
yellow
green
blue
indigo
violet

As you can see, running the script (sort of) works:

It still outputs those silly blank lines though.

Show Me How To Fix The Script

Calm down. Good things come to those who wait/get lucky.

print_my_list_from_file_fixed.py

def print_my_list(my_list):
  for item in my_list:
    print item

def main():
  with open('data.txt') as f:
    my_temporary_list = f.readlines()
	
  my_list = []
  for item in my_temporary_list:
    my_list.append(item.strip())
	
  print_my_list(my_list)

if __name__ == '__main__':
  main()

With this updated script, we now read the data into my_temporary_list.

def print_my_list(my_list):
  for item in my_list:
    print item

def main():
  with open('data.txt') as f:
    my_temporary_list = f.readlines()

The items in my_temporary_list end with pesky newline characters.

(As did the items in the url list in Comments and Files)

To get rid of the newline characters, we step through the items of my_temporary_list, and strip the newline character off the end of each item.

def print_my_list(my_list):
  for item in my_list:
    print item

def main():
  with open('data.txt') as f:
    my_temporary_list = f.readlines()
	
  my_list = []
  for item in my_temporary_list:
    my_list.append(item.strip())

How did I know ‘strip’ does that?

The Python Docs!

Bookmark that URL. You’ll find yourself browsing the docs a lot.

For example, whenever you want to know what you can do with a string, you can just head over to http://docs.python.org/2/library/string.html and have a browse.

strip sounded promising, so I gave it a shot:

I Smell…

Ok, I didn’t need to do that, as stripping whitespace characters (e.g. the newline character) from the end of a string is a very common task.

I already knew the correct operation to use was strip. Go me!

At some point though, I would have consulted the docs.

Since consulting the docs is a two minute task, it’s really not a big deal. I’m not even sure why some folk object to you looking at the docs during programming tests. If anything it shows you possess common sense.

In fact, if anyone ever gives you crap for looking at the docs, I recommend you slap the bejesus out of them.

Seriously…

 

Given time, all the common string operations will imprint themselves in your head without you even realising.

I mean, I never tried to memorize the strip operation. It just somehow found its way into the mushy thing between my ears.

Where Was I?

Once we have a nice new shiny string with the newline character stripped, we append it to my_list.

def print_my_list(my_list):
  for item in my_list:
    print item

def main():
  with open('data.txt') as f:
    my_temporary_list = f.readlines()
	
  my_list = []
  for item in my_temporary_list:
    my_list.append(item.strip())
	
  print_my_list(my_list)

if __name__ == '__main__':
  main()

There’s documentation for lists on python.org as well. To be honest, I don’t think it’s as good as the string docs.

http://docs.python.org/2/library/stdtypes.html

I wouldn’t bother browsing it ‘just in case’. Browse it when you need it – ‘just in time’.

Run The Script

Whenever you update your scripts, you should always jump over to the cmd prompt/terminal and run them. It’s the quickest way to catch any bugs (errors) that you introduce.

As you can see, those pesky blank lines have vanished.

Redirection To A File

Due to my unplanned digression into the Python docs, I haven’t really covered that much in this lesson. As I like to cover a few topics at a time, I’m going to be lazy and show you a ‘quick trick’.

Watch and be amazed!

Basically just run your script as usual, but…

Redirect the contents to a file using the ‘greater than character’. (>)

As you can see, output.txt contains the content that had previously been spat out to the terminal:

Boom! This will be very useful going forward.

Go Do Something

Change the print_my_list function that we've been using, so that it prints the list items in uppercase.

Find the correct string operation to use in the docs:
http://docs.python.org/2.7/library/string.html

Hang On! You know the rules. Go get a coffee first.

Python List Comprehensions

Please Share

If you found this useful, please share with friends.

comments powered by Disqus

Subscribe