编写一个程序,读取一个用逗号分隔的数字文件,并将这些数字打印到海龟屏幕上

Write a program that reads a file with numbers separated by commas and print those numbers to the turtle screen

问题:编写一个程序,从文件中读取数字序列,并将它们显示在图形屏幕上的网格中。对于这个程序,您可以假设有 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()

该程序正在运行,但它只打印文件的最后一行编号。请帮忙!

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()

这是代码的工作版本。注意 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()