问题:编写一个程序,从文件中读取数字序列,并将它们显示在图形屏幕上的网格中。对于此程序,您可以假设每行有4行,每行不超过4个条目。每行的条目用逗号分隔。
例如,考虑一个包含以下内容的文件:
12,13,14,15
8,9,10,11
4,5,6,7
0,1,2,3
这是我的计划:
from turtle import*
def file():
filename = input("Please enter a filename: ")
openfile = open(filename, "r")
readlines = openfile.readlines()
for lines in readlines:
nums = lines.strip().split(",")
return nums
def turtle(n):
row = 0
wn = Screen()
pen = Turtle()
wn.setworldcoordinates(-0.5,3.5,4.5,-1.0)
row = row + 1
pen.up()
for i in range(len(n)):
pen.goto(i,row)
pen.write(i, font=("arial", 30))
row = row + 1
def main():
y = file()
w = turtle(y)
main()
此程序正在运行,但它只打印文件中的最后一行编号。请帮忙!
答案 0 :(得分:0)
from turtle import*
def file():
filename = "t.txt"
openfile = open(filename, "r")
readlines = openfile.readlines()
nums=[]
for lines in readlines:
nums.append(lines.strip().split(","))
return nums
def turtle(n):
print(n)
row = 0
col = 0
wn = Screen()
pen = Turtle()
wn.setworldcoordinates(-0.5,3.5,4.5,-1.0)
pen.up()
for numberRow in n:
for number in numberRow:
pen.goto(col,row)
pen.write(number, font=("arial", 30))
col+=1
row += 1
col = 0
def main():
y = file()
w = turtle(y)
main()
r = input()
答案 1 :(得分:0)
这是代码的工作版本。注意mainloop()调用 从turtle import *,也取消注释第一个with语句并摆脱第二个with语句是你想要用户输入。您的代码,没有正确关闭文件。那绝不是好形式。使用with语句可确保您打开的文件最后关闭。 Python善于回收内存,但你永远不应该把它留给机会,这是确保你回忆起来的好形式。
def file():
#with open(input("Please enter a filename: "), 'r') as data:
with open('test.txt', 'r') as data:
nums = []
for lines in data.readlines():
nums.append(lines.strip().split(","))
return nums
def turtle(n):
wn = Screen()
pen = Turtle()
wn.setworldcoordinates(-0.5,3.5,4.5,-1.0)
row = 0
col = 0
pen.up()
for ele in n:
for i in ele:
pen.goto(row, col)
pen.write(i, font=("arial", 30))
row += 1
row = 0
col += 1
mainloop()
def main():
y = file()
w = turtle(y)
main()