Basics, import. This one is simpler than you may think. When you’re done, your file and interaction should look close to the following code; remember that Python can read a whole file into a string or lines list, and the
lenbuilt-in returns the length of strings and lists:%
cat mymod.pydef countLines(name): file = open(name, 'r') return len(file.readlines()) def countChars(name): return len(open(name, 'r').read()) def test(name): # or pass file object return countLines(name), countChars(name) # or return a dictionary %python>>>import mymod>>>mymod.test('mymod.py')(10, 291)On Unix, you can verify your output with a
wccommand. Incidentally, to do the “ambitious” part (passing in a file object, so you only open the file once), you’ll probably need to use theseekmethod of the built-in file object. We didn’t cover it in the text, but it works just like C’sfseekcall (and calls it behind the scenes);seekresets the current position in the file to an offset passed in. To rewind to the start of a file without closing and reopening, call file.seek (0 ); the file read methods all pick up at the current position in the file, so you need to rewind to reread. Here’s what this tweak would look like:%
cat mymod2.pydef countLines(file): file.seek(0) # rewind to start of file return len(file.readlines()) def countChars(file): file.seek(0) # ditto (rewind if needed) return len(file.read()) def test(name): file = open(name, 'r') # pass file object return countLines(file), ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access