pythondrawturtle-graphicsreadfile

Drawing function, according to the instructions from a text file


I have implemented a small program, that has one function to open and read a text file with instructions for drawing, whereas the second one is targeted at drawing. The second one was already utilised, so it should be correct. The question is that while testing the program, the turtle window opens but literally nothing happened. I think the problem lies in the read_file function. I guess I implemented something in an incorrect way. Was trying to make a 2d list out of the text document but didn't manage to do it. So, the program should open a file with read_file (consequently it should contain "open" method) function and according to extracted instructions draw several spirals. I have just a white screen in turtle window. Guess, drawing process never started

What have I done wrong? Thank you!

from turtle import *


def draw(col, arc_number, basic_radius, rad_growth, pen_weight):

    color(col)
    pensize(pen_weight)
    for i in range(arc_number):
        circle(basic_radius, 90)
        basic_radius += rad_growth


def read_file(name_of_file):
    with open(name_of_file) as filename:
        filename.read().splitlines()
        for spiral in filename:
            for col, arc_number, basic_radius, rad_growth, pen_weight in spiral:
                draw(col, arc_number, basic_radius, rad_growth, pen_weight)


read_file("instruction.txt")
done()

The text file called "instruction.txt" contains color, number of arcs, radius, growth of the radius, pen weight:

black,35,9,6,1
red,15,25,4,2
blue,12,-19,-4,3

(so, there are 3 rows in txt file (1 for each spiral)


Solution

  • In read_file you read in the contents of the file, and split them into lines, but then do nothing with them. There's now nothing left to read in your file, so the loop that follows never runs.

    You likely wanted something more like:

    def read_file(name_of_file):
        with open(name_of_file) as filename:
            for spiral in filename:
                for col, arc_number, basic_radius, rad_growth, pen_weight in spiral.split(','):
                    draw(col, arc_number, basic_radius, rad_growth, pen_weight)
    

    Or rather:

    def read_file(name_of_file):
        with open(name_of_file) as filename:
            for spiral in filename:
                col, arc_number, basic_radius, rad_growth, pen_weight = spiral.split(',')
                draw(col, arc_number, basic_radius, rad_growth, pen_weight)