在文件中添加新行

时间:2011-12-06 17:30:29

标签: python file-io

我想知道每次列表达到棋盘格的大小时如何追加换行符(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)

5 个答案:

答案 0 :(得分:2)

使用

if row_index % 8 == 0:
    # put newline

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

cnt = 0 
for item in pieceList:
    for char in item:
       outputFile.write("%s" %char)
       cnt += 1
       if cnt == 8:
           outputFile.write("\n")
           cnt = 0

答案 3 :(得分:0)

你的意思是你想在每一行后添加换行符吗? 为什么不添加

pieceRow.append("\n")

pieceList.append(pieceRow)

答案 4 :(得分:0)

您可以使用枚举,

例如,     CONST_SIZE = 8

for index, item in enumerate(item_list):
    output_file.write(item)
    if index % 8 == 0: output_file.write('\n')

每次向文件写入8个项目时,都会附加换行符。