

Reading Files (Python in 30 Days - Day 5) - rodriguezcommaj
http://rodriguezcommaj.com/python-in-30-days-day-5/

======
ColinWright
These are pointers for the future, you're probably not ready for them yet in
your journey, but I have a few thoughts for you.

    
    
        # Import your modules
        from sys import argv
    
        # unpack argv
        script, filename = argv
    

If zero or more than one arguments were passed on the command line, this will
throw an error. You need to think about what your program should do in those
cases.

    
    
        # assign the opened file from argv to the variable txt
        txt = open(filename)
    

"txt" is a bad name. This is a file handle, or open file object, it is not
text. Consider using a name that describes what it is or does.

Also, what happens if the file doesn't exist?

    
    
        # print what you opened and then read the file to the console
        print "Here's your file %r: " % filename
        print txt.read()
    

Once you are done with a file it is polite to close it: txt.close(). This
isn't essential in Python because it will eventually be garbage collected and
the close will be called for you, but it's worth knowing.

    
    
        # get the filename from the user and assign it to the file_again variable
        print "Type the filename again: "
        file_again = raw_input("> ")
    
        # open that file and assign the opened file to the variable txt_again
        txt_again = open(file_again)
    

And again, bad variable name.

    
    
        # read that file to the console
        print txt_again.read()
    

And again, it's polite to close the file when you're done with it.

~~~
RyanMcGreal
Even better when handling files is to use the with statement.

    
    
        with open(filename, 'r') as myfile:
            data = myfile.read()
            # do something with data
    

The nice thing about with is that it doubles as a try...except block and
automatically closes the file for you.

~~~
ColinWright
Yes, but when you're just three days into learning it's good to do things the
direct way using fewer language facilities, then grow into the more powerful
constructs later when you can better appreciate their value.

