如何在Python中将文件内容打印到控制台

时间:2016-02-29 16:04:10

标签: python python-2.7

我想将包含4x4数字网格的文本文件打印到控制台,但我的代码不起作用。有什么建议吗?

  def Viewfile(self):
    try:
        viewFileOpen=open(self.viewFileName,'r')
        for viewLine in viewFileOpen:
            self.theViewBoard.append(viewLine)
        print self.theViewBoard
        '''

我曾经尝试过,有没有拆分

        viewFileOpen=open(self.viewFileName,'r')
        for viewLine in viewFileOpen:
            viewListofValues=viewLine.split()
            viewRow=[]

            for viewItem in viewListofValues:
                viewRow.append(viewItem)
            self.theViewBoard.append(viewRow)
        print self.theViewBoard'''
    except:
        print"Some Error In getting the file printed at the end"

1 个答案:

答案 0 :(得分:4)

您可以只读取文件并将其打印到控制台,如下所示:

def Viewfile(self):
    with open(self.viewFileName,'r') as viewFileOpen:
        data = viewFileOpen.read()
    print(data)