如果指定了文件,则创建并打印到新文件,否则只需std.ou

2024-10-04 03:23:41 发布

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

我在制作宾果卡。任务的一部分是将卡片打印到屏幕上,除非用户指定了一个文件,在这种情况下,它会将卡片打印到该文件上。我将创建他们指定的文件

我已经把它完美地打印到了屏幕上,但是我不知道如何创建文件并把宾果卡打印到上面。我知道我可以使用open(file) as ff.write,但是当我这样做的时候,它总是出现错误,我不能再打印到stdout了

有什么建议吗?这是代码,我的老师指定了函数名,我只要把代码填上就行了。我用test.print()来称呼它

def print(self, file=sys.stdout):
    """void function:
    Prints a card to the screen or to an open file object"""
    # if file == sys.stdout:
    #     f = sys.stdout
    # else:
    #     f = open(str(file), 'w+')
    tableCorner = "+"
    tableMiddle = "-----"
    tableSide = "|"
    total = 0
    row = 0
    print("\nCard #" + str(self.getId()))
    while row < self.size:
        # prints horizontal divider
        while total < self.size:
            print(tableCorner + tableMiddle, end="")
            total += 1
        print(tableCorner)
        total = 0
        # prints line with numbers
        while total < self.size:
            print(tableSide + str(self.card.getNext()).center(5, " "), end="")
            total += 1
        print(tableSide)
        total = 0
        row += 1
    while total < self.size:
        print(tableCorner + tableMiddle, end="")
        total += 1
    print(tableCorner)

Tags: 文件selfsizestdoutsysopenfilerow
1条回答
网友
1楼 · 发布于 2024-10-04 03:23:41

不要将sys.stdout设置为默认参数,请尝试:

def print(self, file=None):
    if not file is None:
        sys.stdout = open(file)

剩下的代码保持不变。将sys.stdout设置为file对象将导致打印结果出现在那里,而不是正常的stdout。请记住,通常不建议在with块外部使用open,因此您可能需要相应地重新构造内容

编辑:两件事: 1.我做了一个快速演示,演示了将sys.stdout设置为文件对象时会发生什么:

In [1]: import sys                                                              

In [2]: print('some BODY once told me')                                         
some BODY once told me

In [3]: sys.stdout = open('test.txt','w')                                       
In [4]: print('some BODY once told me')                                         
In [5]: sys.stdout = sys.__stdout__                                             

In [6]: with open('test.txt','r') as f: 
   ...:     print(f.read()) 
   ...:                                                                         

some BODY once told me

如您所见,在不更改sys.stdout的情况下,打印将在ipython控制台中返回。将其更改为一个名为text.txt的文件后,它将在那里结束,并通过将sys.stdout放回原始文件(由sys.__stdout__给出)进行验证,然后打印出文件的内容

  1. 您可能不需要担心使用with块。在将sys.stdout设置为file对象后尝试关闭它时出错:

回溯(最近一次呼叫): 文件“/home/finchj/programs/anaconda3/envs/finchj/bin/ipython”,第11行,in 系统退出(启动ipython()) 文件“/home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site packages/IPython/init.py”,第125行,在start\u IPython中 返回启动新实例(argv=argv,**kwargs) 文件“/home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site packages/traitlets/config/application.py”,第658行,在launch\u实例中 app.start() 文件“/home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site packages/IPython/terminal/ipapp.py”,第356行,开始 self.shell.mainloop() 文件“/home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site packages/IPython/terminal/interactiveshell.py”,第498行,在mainloop中 self.interact() 文件“/home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site packages/IPython/terminal/interactiveshell.py”,第478行,在interact中 打印(self.separate\u in,end='') ValueError:对关闭的文件执行I/O操作

这让我怀疑清理工作是在幕后进行的,尽管目前我无法证实这一点

相关问题 更多 >