Reading Files (Python in 30 Days - Day 5)
rodriguezcommaj.com
rodriguezcommaj.com
# 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. 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.I definitely appreciate you weighing in on it, I love seeing this type of feedback from HN users. Makes me excited to keep learning and become a part of the community.
Personally, I strongly dislike camel-casing, and never use it in my own code.
I'll admit that's oldschool, and use lots of short variable names, often abbreviated. This tends to be less of a source of error than a typoInAnExtremlyLongAndVerboseVariableName.