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

时间:2019-03-05 04:12:30

标签: python printing

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

我已经将它完美地打印到屏幕上了,但是我不知道如何创建文件并在其中打印宾果卡。我知道我可以使用open(file) as ff.write,但是当我这样做时,它会不断出现错误,我无法再打印到标准输出了。

有关如何执行此操作的任何建议?这是代码,我的老师指定了函数名称,我只需要填写代码即可。我用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)

1 个答案:

答案 0 :(得分:0)

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

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

,其余代码保持不变。将sys.stdout设置为文件对象将导致打印结束而不是正常的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设置为等于文件对象后尝试关闭它会给我一个错误:

回溯(最近通话最近):   在第11行的“ / home / finchj / programs / anaconda3 / envs / finchj / bin / ipython”文件中     sys.exit(start_ipython())   在start_ipython中的第125行中,文件“ /home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site-packages/IPython/init.py”     返回launch_new_instance(argv = argv,** kwargs)   文件“ /home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site-packages/traitlets/config/application.py”,行658,在launch_instance中     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行     self.interact()   在互动中的文件“ /home/finchj/programs/anaconda3/envs/finchj/lib/python3.6/site-packages/IPython/terminal/interactiveshell.py”,行478     打印(self.separate_in,end ='') ValueError:对关闭的文件进行I / O操作。

虽然我现在不能确定是这种情况,但还是让我怀疑清理是在后台进行的。