So how to design the for-loop to begin counting at the 5th-to-final-line and to stop at line 4766? We already know how to use the range() function to create a range of numbers from x to y ( x and y are arguments representing, respectively, the start and end points of the range): for n in range ( 42, 48 ): print ( n ) A hardcoded advance The output will be: tempdata/tragedies/romeoandjuliet has 4766 lines close () print ( fname, "has", line_num, "lines" ) join ( 'tempdata', 'tragedies', 'romeoandjuliet' ) txtfile = open ( fname, 'r' ) line_num = 0 for x in txtfile : line_num += 1 txtfile. Now let's count it programmatically revisiting the code from the previous exercise, in which we counted every line in Hamlet, here's how to count every line in Romeo and Juliet (basically, it's the same code, just change the filename): import os fname = os. Though the last line number in the text editor is 4767 – it's a blank line (i.e. Let's do a manual check with the text editor: If we want to print the final 5 lines in Romeo & Julet, we need to know how many lines there are in the first place. ![]() ![]() We're going to solve this exercise in the most straightforward way possible, even if it seems a little wasteful and inefficient. The program's output to screen should be:Ĥ762: Some shall be pardon'd, and some punished: ![]() When you run f.py from the command-line: 0004-shakefiles $ python f.py
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |