【发布时间】:2011-10-21 23:34:18
【问题描述】:
我有一个文本文件,其中包含圆心的 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
我想出的整个程序运行良好,除了一个部分。我使用 for 循环从文件中获取信息,根据需要将其拆分,然后将圆圈绘制到 GraphWin。
问题是,文本文件中有15个圆圈的数据,但是for循环只读取了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()
如何让它不跳过文本文件中的第一行?我已经在互联网和这里搜索过这个问题,但通常我得到的是人们问如何跳过行,这与我需要的相反。
【问题讨论】:
-
啊!!当 int() 可以使用时不要使用 eval()。
-
文体注释:在 Python 中,空格优于制表符。
标签: python file-io python-3.x