dsaa30
dsaa30
23 # The strip method strips off the newline character at the end of the line
24 # and any blanks that might be at the beginning or end of the line.
25 text = line.strip()
26
27 # The following line splits the text variable into its pieces.
28 # For instance, if text contained "goto, 10, 20, 1, black" then
29 # commandList will be equal to ["goto", "10", "20", "1", "black"] after
30 # splitting text.
31 commandList = text.split(",")
32
33 # get the drawing command
34 command = commandList[0]
35
36 if command == "goto":
37 # Writing float(commandList[1]) makes a float object out of the
38 # string found in commandList[1]. You can do similar conversion
39 # between types for int objects.
40 x = float(commandList[1])
41 y = float(commandList[2])
42 width = float(commandList[3])
43 color = commandList[4].strip()
44 t.width(width)
45 t.pencolor(color)
46 t.goto(x,y)
47 elif command == "circle":
48 radius = float(commandList[1])
49 width = float(commandList[2])
50 color = commandList[3].strip()
51 t.width(width)
52 t.pencolor(color)
53 t.circle(radius)
54 elif command == "beginfill":
55 color = commandList[1].strip()
56 t.fillcolor(color)
57 t.begin_fill()
58 elif command == "endfill":
59 t.end_fill()
60 elif command == "penup":
61 t.penup()
62 elif command == "pendown":
63 t.pendown()
64 else:
65 print("Unknown command found in file:" ,command)
66
67 #close the file
68 file.close()
69
70 #hide the turtle that we used to draw the picture.
71 t.ht()
72
73 # This causes the program to hold the turtle graphics window open
74 # until the mouse is clicked.
75 screen.exitonclick()
76 print("Program Execution Completed.")
77
78
79 # This code calls the main function to get everything started.
80 if __name__ == "__main__":
81 main()
Listing 1.12 Reading and Processing Single Line Records
When you have a data file where each line of the file is its own separate record,
you can process those records as we did in Listing 1.12. The general pattern is to
open the file, use a for loop to iterate through the file, and have the body of the for
loop process each record. The pseudo-code in Listing 1.13 is the abstract pattern for
reading one-line records from a file.