12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Incidentally, to do the “ambitious” part of this exercise (passing in a file object,so you only open the file once), you’ll probably need to use the seek method ofthe built-in file object. We didn’t cover it in the text, but it works just like C’sfseek call (and calls it behind the scenes): seek resets the current position in thefile to a passed-in offset. After a seek, future input/output operations are relativeto the new position. To rewind to the start of a file without closing and reopeningit, call file.seek(0); the file read methods all pick up at the current positionin the file, so you need to rewind to reread. Here’s what this tweak would looklike:def countLines(file):file.seek(0)return len(file.readlines( ))# Rewind to start of filedef countChars(file):file.seek(0)return len(file.read( ))def test(name):file = open(name)return countLines(file), countChars(file)# Ditto (rewind if needed)# Pass file object# Open file only once>>> import mymod2>>> mymod2.test("mymod2.py")(11, 392)2. from/from *. Here’s the from * part; replace * with countChars to do the rest:% python>>> from mymod import *>>> countChars("mymod.py")2913. _ _main_ _. If you code it properly, it works in either mode (program run or moduleimport):def countLines(name):file = open(name)return len(file.readlines( ))def countChars(name):return len(open(name).read( ))def test(name):return countLines(name), countChars(name)# Or pass file object# Or return a dictionaryif __name__ == '_ _main_ _':print test('mymod.py')% python mymod.py(13, 346)4. Nested imports. Here is my solution (file myclient.py):from mymod import countLines, countCharsprint countLines('mymod.py'), countChars('mymod.py')662 | Appendix B: Solutions to End-of-Part Exercises

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!