Opening Files in Python

Opening Files in Python

So right now I am learning how to open and read files in Python, which is exercise 15. Apparently, it gets super hard around the 30 exercise mark. I am looking forward to the challenge, however.

So I am working through exercise 15. The text file we are to open and read in python contains some arbitrary text. We are still working with argument variables and the command raw_input(), but we’re throwing in the argv


with another command


which just opens the file taking a parameter which returns a value, kind of like raw_input, that you can set to any variable you want, according to pydoc (which is the document system built into python– excellent resource, aside from Dash).

Here is the script I wrote:

from sys import argv

script, filename = argv

txt = open(filename)

print “Here’s your file %r:” % filename

print “Type the filename again:”
file_again = raw_input(“> ”)

txt_again = open(file_again)


Here is my script with the comments I wrote, an annotation that Zed Shaw encourages.

#Grabs the sys module and the argv variable inside that module

from sys import argv

#sets the argument variables to script and filemane</h1>

script, filename = argv

#when we type the script into the terminal, you have to type in the filename as well that you want to open. This filename must be an arguement variable when you run the python script. txt indicates that it is a txt file. Open(filenmae) calls the argument variable that we specified was ex15_sample.txt and opens it, taking a parameter and returning a value you can set as your own value, much like raw_input

txt = open(filename)

#this line prints out text and opens an formatter which is the argument variable filename.

print “Here’s your file %r:” % filename

#here we call a function on the text file which is read(). To give a file a command you use the dot and and function so opens the file without getting any parameters.


#this line prints this line of text in the script in terminal

print “Type the filename again:”

#this is another prompt with raw_input and the caret assigned to the variable file_again. You must type in the name of the text file again or python will throw an error

file_again = raw_input(“> ”)

#this line uses the open command to open the txt file again

txt_again = open(file_again)

#this line uses the function read() which is part of the command you’re giving the file It will then read and print the contents of the file.



Argument Variables and ValueErrors in Python

Going through more Zed Shaw tutorials with Learn Python the Hard Way and finding it excellent as it gets more challenging. We are working with argument variables, which hold the arguments you pass through your python script until called later.

He let us know that part of the command:


was an argument, that part being:

We then wrote a script that accepted arguments. First, the first line of the script was:

from sys import argv

Importing lets you add modules to your python script. Instead of piling in modules, python let’s you choose which ones you want. In this case we have the sys or system module. I am not sure what a system module is or what modules do yet, as I am at exercise 14 and still working through it.

Next we have the argument variables:

script, first, second, third = argv

We call these variables, I am not sure if the correct word is call, I know it is for object-oriented programming, and I am not sure if python relies on objects like Ruby. But anyway…

This was the part of the script that would run when called in terminal:

print “The script is called:”, script
print “Your first variable is:”, first
print “Your second variable is:”, second
print “Your third variable is:”, third

When first running this in terminal I got a ValueError returned to me:

Traceback (most recent call last):
File “”, line 3, in
script, first, second, third = argv
ValueError: need more than 1 value to unpack

It seemed that I didn’t reference enough arguments. I then reread the tutorial and saw that I needed to specify the arguments by typing in a random name:

python first 2nd 3rd
The script is called:
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd

I replicated this according to the tutorial, trying to understand what the error was. I was a bit confused. I thought that I had four arguments, not five when I typed the following in:

python first 2nd
Traceback (most recent call last):
File “”, line 3, in
script, first, second, thrid = argv
ValueError: need more than 3 values to unpack

I was literally stuck on this. Went into the Code Newbie Slack team looking for help and voila! I got some from the truly smart people there. I forgot that was an argument as well. So I did only have four arguments. In the last example, my three unpacked arguments were,, first, and 2nd. I needed one more, not 3. It may sound weird but my mind was lost.

So now that I know that I moved onto exercise 14, mixing in prompts with argument variables, format variables, and the like.

Here is the script:

from sys import argv

script, user_name = argv
prompt = ‘>’

print “Hi, %s, I’m the %s script.” % (user_name, script)
print “I’d like to ask you a few questions.”
print “Do you like me %s?” % user_name
likes = raw_input(prompt)

print “Where do you live %s?” % user_name
lives = raw_input(prompt)

print “What kind of computer do you have?”
computer = raw_input(prompt)

print \"\"“
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have %r computer. Nice.
”\"\" % (likes, lives, computer)

Took me a bit to get that I was assigning a prompt to variables. I didn’t get that until I got to the last code block.

And here is another gif of the result:


Going through Python and Ruby with Zed Shaw

You remember when I said I was going to do The Odin Project and Codecademy? Well, I have an even better solution.
First off, let me say that learning HTML and CSS all day is great if you want to do web dev and that is what I want to do, maybe. I am finding that building apps and scripts is fun. The reason I am doing Python now is because of my Raspberry Pi. I wanted to program it this summer and I know very little Python so I looked for a good alternative to the Codecademy Python course which was just a fragmented bit of Python learning. I wasn’t grasping the concepts, nor was I being asked to think about the things I was learning.

So I remembered fro Code Newbie Podcast Zed Shaw. He had written a book called Learn Python the Hard Way and offered it up for free as HTML on the book’s website. So I went. And I started. And I’m hooked.

So what made it great? Study Drills. Enforcing the fact that you should type everything on the screen, use a text editor and not an IDE (which I was really tempted to do) and the questions he answers from previous students. You get to practice what you learn, to, by building little scripts on your own. Here is an example of a form script I wrote using Python, from exercise 11 Study Drill:

print “What is your occupation?”,
occupation = raw_input()
print “How many kids do you own?”,
kids = raw_input()
print “Do you like cats? Answer like or do not like”,
cats = raw_input()
print “What is your reputation on Stack Overflow”,
stack_overflow = raw_input()

print “So you do %r, own %r kids, %r cats, have a reputation of %r on Stack Overflow.” % (
occupation, kids, cats, stack_overflow)

Learned so far:

Format variables like %r can input data within a string. You can call format variables later in a string, by using:

Name = ‘Zed A. Shaw’
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = ‘Blue’
teeth = ‘White’
hair =’Brown’
metric_height = height * 2.54
metric_weight = weight * 0.453592

print “Let’s talk about %s.” % Name
print “He’s %d inches tall.” % height
print “He’s %d pounds heavy.” % weight
print “That’s actually not too heavy.”
print “He’s go %s eyes and %s hair.” % (eyes, hair)
print “His teeth are usually %s depending on the coffee.” % teeth
print “The metric system is odd as my %f and %f are different” % (metric_weight, metric_height)
# this line is tricky, try to get it exactly right
print “If I add %d, %d, and %d I get %d.” % (age,
height, weight, age + height + weight)
print “In England my height %d and weight %d are %f and %f.” % (height, weight,
metric_height, metric_weight)
print “If I add %d, %d, %f and %f I get %f.” % (height, weight, metric_weight, metric_height,
height + weight + metric_weight + metric_height)

As you can see, I assigned a variable before using the print command, called those same variables later in subsequent strings by using format variables.

Another thing learned:


This won’t format the user input as Python code and is used as a promt. So if you look about on the form I made, when run in terminal:


You can see it prompts the user. Cool, huh?

This tutorial out of all the ones I’ve tried is really building my confidence. Here’s to more late nights in the trenches.