简体   繁体   中英

How to print contents on file to console in Python

I want to print a text file containing 4x4 grid of numbers to the console but my code isn't working. Any suggestions?

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

I have tried with and without split here

        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"

You could just read the file and print that to the console like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM