Page 112 -
P. 112
idle session
Start a new IDLE sesson and import the os module to change the current working directory to the folder that
contains your just-downloaded data file:
>>> import os Import “os” from the Standard Library.
>>> os.getcwd() What’s the current working directory?
'/Users/barryp/Documents' Change to the folder that contains your data file.
>>> os.chdir('../HeadFirstPython/chapter3')
>>> os.getcwd() Confirm you are now in the right place.
'/Users/barryp/HeadFirstPython/chapter3'
Now, open your data file and read the first two lines from the file, displaying them on screen:
>>> data = open('sketch.txt') Open a named file and assign the file to a file object called “data”.
>>> print(data.readline(), end='')
Use the “readline()” method to grab a
Man: Is this the right room for an argument?
>>> print(data.readline(), end='') line from the file, then use the “print()”
Other Man: I've told you once. BIF to display it on screen.
Let’s “rewind” the file back to the start, then use a for statement to process every line in the file:
>>> data.seek(0) Use the “seek()” method to return to the start of the file.
And yes, you can use “tell()” with Python’s files, too.
0
>>> for each_line in data:
print(each_line, end='') This code should look familiar: it’s a standard
iteration using the file’s data as input.
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have. Every line of the data is
Man: When? displayed on screen (although
for space reasons, it is
Other Man: Just now. abridged here).
Man: No you didn't!
...
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
>>> data.close() Since you are now done with the file, be sure to close it.
76 Chapter 3