(Python 3.2)Python上的文件处理?

2024-06-07 10:46:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。这是一个TXT文件中的文本行,作业要求我在图形窗口中打印它们

student1 lastname 55
student4 lastname 55
student9 lastname 55
student10 lastname 55
student12 lastname 55
student15 lastname 55

因此,首先我打开文件,进入这个循环并将它们打印在python shell上。你知道吗

file = open("input.txt","r")
    for line in file:
        print(line)

我的图形窗口代码

from graphics import *   
win = GraphWin('', 600,500)

现在如何在我刚刚创建的图形窗口中打印这些文本行?你知道吗


Tags: 文件文本txt图形作业lineshellfile
2条回答

你做得很好,但你应该read the docs为了更好的理解。你知道吗

做你想做的事的更好的方法是

from graphics import *
win = GraphWin('', 600,500)
text_x, text_y = 200, 50
with open("input.txt","r") as file:
    for line in file:
        print(line)
        label = Text(Point(text_x, text_y), line)
        label.draw(win)
        text_y += 50 # distance between 2 lines

您可以使用基本的列表操作将行放入列表中,如

line = [line.strip() for line in open("file.txt")]

一旦您得到了这个列表,就可以访问窗口中for循环中的每个元素

我建议你通读这篇 pythongraphics doc

相关问题 更多 >

    热门问题