HomePython Page 3 - Python 101 (part 5): Snake Oil For The Soul
Treading The Right Path - Python
Now that you know how to create and use Python's tuples, listsand dictionaries, it's time to get your hands dirty. In this article, findout how to read from, and write to, files on the filesystem with built-inPython methods, and also take a look at some of the new features availablein Python 2.x.
You could write a Python program that accomplishes the same thing:
# open file
data = open("snakeoil.txt")
# read file
dump = data.read()
print dump, "-- EOF -- EOF --"
# clean up
And when you run this script, Python should return the contents of the file"snakeoil.txt", with a message at the end.
After years of research, scientists at AB Labs have come up with a radical
new product, once that promises to improve the quality of life for humans
and animals everywhere.
We call it Air In A Bottle(tm), and we firmly consider it to be one of our
best inventions ever.
Carry it around with you (the bottle is titanium, the same material used in
rocket ships, and the air is, well, air) and inhale from it whenever you
need some air. Or give it to your friends as a present (after all, they
need air too!)
Air In A Bottle(tm). Get some today!
-- EOF -- EOF --
Notice that since this is being run as a script and not via thecommand-line interpreter, the \012s are automatically converted into linebreaks.
And look what happens if the file doesn't exist:
>>> data = open("/tmp/nosuchfile.txt")
Traceback (innermost last):
File "", line 1, in ?
IOError: [Errno 2] No such file or directory: '/tmp/nosuchfile.txt'