向fi追加新行

2024-10-01 13:25:46 发布

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

我想知道如何在每次列表达到棋盘格(8)的大小时追加一行新行。这是我目前为止的代码。它可以工作,但我想每8个字符加一个换行符。在

 saveFile=input("Please enter the name of the file you want to save in: ")
  outputFile=open(saveFile,"w")
  pieceList=[]
  for row_index in range (self.SIZE):
     for column_index in range(self.SIZE):
        pieceRow=[]
        char=" "
        if self.grid[row_index][column_index]==Piece(Piece.WHITE):
           char="w"
        elif self.grid[row_index][column_index]==Piece(Piece.RED):
           char="r"
        pieceRow.append(char)
     pieceList.append(pieceRow)
     for item in pieceList:
        for char in item:
           outputFile.write("%s" %char)

Tags: theinselfforsizeindexpiecerange
3条回答

使用

if row_index % 8 == 0:
    # put newline
cnt = 0 
for item in pieceList:
    for char in item:
       outputFile.write("%s" %char)
       cnt += 1
       if cnt == 8:
           outputFile.write("\n")
           cnt = 0
saveFile=input("Please enter the name of the file you want to save in: ")
  outputFile=open(saveFile,"w")
  pieceList=[]
  characterCounter =0
  for row_index in range (self.SIZE):
     for column_index in range(self.SIZE):
        pieceRow=[]
        char=" "
        if self.grid[row_index][column_index]==Piece(Piece.WHITE):
           char="w"
        elif self.grid[row_index][column_index]==Piece(Piece.RED):
           char="r"
        pieceRow.append(char)
        characterCounter++
        if characterCounter==8:
           pieceRow.append("\n")
           characterCounter=0
     pieceList.append(pieceRow)
     for item in pieceList:
        for char in item:
           outputFile.write("%s" %char)

相关问题 更多 >