Python 3.2.1:从文本文件读取错误

2 投票
1 回答
989 浏览
提问于 2025-04-17 04:47

我有一个文本文件,里面记录了一个圆的中心坐标(x和y),接着是半径和填充颜色。

文本文件的内容(供参考):

30,50 12 goldenrod
78,75 10 coral
14,79 11 tomato
32,77 12 maroon
21,25 15 burlywood
24,67 14 sienna
62,93 13 chartreuse
24,42 16 olivedrab
79,18 10 peachpuff
18,61 19 thistle
15,27 11 mediumpurple
84,87 12 cornsilk
77,25 11 linen
74,96 15 honeydew
63,15 13 dodgerblue

我写的整个程序运行得很好,除了有一个地方。我用一个循环来读取文件中的信息,必要时进行分割,然后把圆画到图形窗口(GraphWin)上。

问题是,文本文件里有15个圆的数据,但这个循环只读取了14个圆,完全跳过了第一行。

代码如下:

def myCircles():
    path = "C:\\"
    extension = ".txt"
    center = ""
    radius = ""
    color = ""
    lines = ""

    fname = input("Please enter the name of the file where the data is stored. The path [C:\\...] and extension [*.txt] are not needed: ") or "TestDataCircles"

    inFile = open(path + fname + extension, "r")

    win = GraphWin("WSUTC CptS111-Q2", 500, 500)
    win.setCoords(0, 0, 100, 100)

    lines = inFile.readline()

    for lines in inFile.readlines():
        center, radius, color = lines.split()
        centerx, centery = center.split(",")
        centerx, centery = eval(centerx), eval(centery)

        ccenter = Point(centerx, centery)

        myCircle = Circle(ccenter, eval(radius))
        myCircle.setFill(color)
        myCircle.draw(win)

    inFile.close()

    print("Please click anywhere inside the graphics window to close it.")
    win.getMouse()
    win.close()

我该怎么做才能让它不跳过文本文件的第一行呢?我在网上和这里搜索过这个问题,但大多数人讨论的是如何跳过某些行,这正好和我需要的相反。

1 个回答

6

我觉得你只需要在你的循环之前去掉这一行:

lines = inFile.readline()

这一行是在读取文件的第一行,但你并没有对它做任何处理,然后才开始逐行读取文件。

撰写回答