PYTHON 3:读取文件并将坐标映射到龟屏幕

时间:2015-05-05 01:33:37

标签: python format turtle-graphics

所以我必须编写一个程序来读取包含地震数据的csv文件,然后只从文件中获取纬度和经度并将其映射到Python 3中的海龟屏幕。

这是CSV file

我的节目:

import turtle
def drawQuakes():
 filename = input("Please enter the quake file: ")
 readfile = open(filename, "r")
 readlines = readfile.read()

 start = readlines.find("type")
 g = readlines[start]
 Type = g.split(",")
 tracy = turtle.Turtle()
 tracy.up()
 for points in Type:
     print(points)
     x = float(Type[1])
     y = float(Type[2])
     tracy.goto(x,y)
     tracy.write(".")
drawQuakes()

我知道这个程序相当容易,但我一直收到这个错误:

x = float(Type[1])IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

您没有正确使用该文件,请将其分解:

readlines = readfile.read()
# readlines is now the entire file contents

start = readlines.find("type")
# start is now 80

g = readlines[start]
# g is now 't'

Type = g.split(",")
# Type is now ['t']

tracy = turtle.Turtle()
tracy.up()
for points in Type:
    print(points)
    # points is 't'

    x = float(Type[1])
    # IndexError: list index out of range

    y = float(Type[2])
    tracy.goto(x,y)
    tracy.write(".")

我会使用csv.DictReader:

import turtle
import csv

def drawQuakes():
    filename = input("Please enter the quake file: ")

    tracy = turtle.Turtle()
    tracy.up()

    with open(filename, 'r') as csvfile:
        reader = reader = csv.DictReader(csvfile)
        for row in reader:
            if row['type'] == 'earthquake':
                x = float(row['latitude'])
                y = float(row['longitude'])
                tracy.goto(x,y)
                tracy.write(".")

drawQuakes()

enter image description here