简体   繁体   中英

Plotting map with coordinate from a csv file using Python turtle

Ι am trying to plot a map from a csv file using turtle graphic.

My csv file is here: http://textuploader.com/5nau2

My program:

import turtle
import csv
import math

def drawMap():
    filename = "C:\python-exercises\coordinates1.csv"

    trace = turtle.Turtle()
    trace.up()

    #scr = Screen()

    with open(filename, 'r') as csvfile:
        reader = reader = csv.DictReader(csvfile)
        for row in reader:

            x = (row[0])
            y = (row[1])
            trace.goto(x,y)
            trace.write(".")
    raw_input()
    #scr.mainloop()
drawMap()

But it is not displaying anything, and also generates errors like:

x = row([0])

keyError: 0

The following should get you started. The file you are trying to read in is not in csv format, so instead of using the csv library you could read the rows in yourself as follows:

import turtle
import math

def drawMap():
    filename = r"C:\python-exercises\coordinates1.csv"

    trace = turtle.Turtle()
    trace.up()

    #scr = Screen()

    with open(filename, 'r') as f_input:
        for row in f_input:
            row = row.strip('()\n').split(',')
            x = float(row[0])
            y = float(row[1])
            trace.goto(x,y)
            trace.write(".")
    raw_input()
    #scr.mainloop()
drawMap()

This takes each row, removes the outer parenthesis and newline and splits it into two columns. The columns are then converted to floats for your turtle program to interpret.

If you are ever not sure about why something is not working, add some print statements to see what is happening.

Also, do not forget to prefix your filename path with r , this stops Python from trying to interpret the backslashes in your string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM