Python Comments and Reading Files

At the end of Python Function Arguments, I left you with the task of updating the 'days of the week' script to print the colours of the rainbow.

Without further ado, you should have modified it to look something like this:

I've highlighted the 2 lines that differ from the 'days of the week' script.

What's That Line Beginning With a #?

That's a comment. The Python interpreter just ignores it. It's there for any humans who read the script.

In this case, I've just put a link to the webpage that I grabbed the colours of the rainbow from.

I pronounce '#' as 'hash' by the way. Some folk call it 'pound'.

Why did I need to look up the colours of the rainbow?

I'm from Scotland, and I vaguely remember a nursery song that went 'red and yellow and pink and green, and purple and orange and blue'.

Since I have my big boy pants on these days, I thought I'd see what the actual colours of the rainbow are.

Reading Data From a File

Lets separate out our data and our logic. This will allow us to bump some work onto someone else.

For example, I could say to my intern:

'Can you send me a text file with a list of URLs, one URL on each line'

I don't actually have an intern, but one can dream...

They'd send over something like this:

I could then pull this data into my script and turn it into a list:

Now imagine that text file was massive. I've just saved myself a good whack of time by delegating the data collection task to someone else.

Don't get too hung up on memorizing the above snippet. It's a very common idiom that you'll see over and over again.

This bit opens and closes (the big red arrow pointing at the un-indent) the 'data.txt' file, that sits in the same directory as  input_from_a_file.py

This bit reads the lines in our file and gives back a list_of_urls

Run The Script

Running the script should just echo back the URLs in data.txt

Let's give it a bash:

It almost does that.

Why's there a blank line between each URL though?

Ok, don't panic here.. I'm going to dive into the python shell to show you something.

See that big red arrow pointing at '\n' (backslash n). That's a 'newline character'. The python print statement takes a newline for us, so this additional newline at the end of each URL is messing up our script.

I'll show you how we can fix this in Chapter 5.

Go Do Something

Update your 'colours of the rainbow' script to read in the data from a file. It should be very similar to input_from_a_file.py

Python Docs and File Redirection

Please Share

If you found this useful, please share with friends.

comments powered by Disqus

Subscribe