Learning Python The Hard Way Example 15 Python shell problems
Question: As the title says, I'm having issues with running commands through python
shell, more specifically, I can't seem to figure out how to open and read
files like it tells me to do in the study drill.

here's everything I've done so far:

    
    
    PS C:\Users\NikoSuave\Desktop\learn python the hard way\works in progress or finished> python
    Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from sys import argv
    >>> script, filename = argv
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: need more than 1 value to unpack
    >>> txt = open(filename)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'filename' is not defined
    >>> filename = argv
    >>> script = argv
    >>> txt = open(filename)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: coercing to Unicode: need string or buffer, list found
    

what am I doing wrong? and If i'm way off, could one of you please point me in
the right direction?


Answer: `sys.argv` is a list in Python, which contains the command-line arguments
passed to the script. So this is generally used when you run a python prog.
using command line like:

    
    
    python prog.py arg1 arg2
    

Here `arg1` and `arg2` are present in the `argv` list. While being in REPL no
arguments are passed to hence `argv` is empty. This is the reason you keep
getting `ValueError`, `NameError`...

As for opening a file, it like: `file_object = open(filename, mode)` where
`mode` can be `r, w, a, r+` (read, write, append and both read-write). An
example would be:

    
    
    file = open("newfile.txt", "w")
    file.write("hello world in the new file\n")
    file.write("and another line\n")
    file.close()
    

The code above opens `newfile.txt` for write and adds the content shown.
Finally closes the file. Similar thing is available while reading the file:

    
    
    file = open("newfile.txt", "r")
    print file.read()
    

This reads the file `newfile.txt` and prints the content.

