Python Forum

Full Version: Matt's newb question 1
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm working through a book called Learn Python The Hard Way. I'm on an exercise (15) where the author asks you to comment in explanations of what each line of code does. Could you look at my code and explanations and tell me what the right explanations are and if I got any of them right?

Thanks,

Matt

# I'm not sure what these do exactly. I think import argv imports the argv library.
from sys import argv
# This line makes it so that this script's activation requires the name of it and another input which is the name of the
# file to be opened
script, filename = argv
# creates a variable called txt which functions as to open the file stated in "file name"
txt = open(filename)
# prints a string that contains the name of the file
print "Here's your file %r:" % filename
# prints out the contents of the file represented by "txt"
print txt.read()
# prints a string 
print "Type the filename again:"
# this line creates a variable "file_again" whose contents are supplied by the user. The contents are the txt file name.
file_again = raw_input("> ")
# creates a variable "txt_again" whose contents were supplied by the input the user made in "file_again"
txt_again = open(file_again)
# prints the "file_again" that was opened in the variable txt_again
print txt_again.read()
1. sys is a module that contains "system functionality". sys.argv is a list containing your script's command line arguments. One way to use it would be to write import sys and then sys.argv to access it.

from module import names is an alternative way to import a module that allows you to access the given names without naming the module. That is writing from sys import argv allows you to just write argv whereas import sys would require you to write sys.argv instead.


2.https://stackoverflow.com/questions/13666346/from-sys-import-argv-what-is-the-function-of-script

3-9 are all correct.