2011-12-06 117 views
0

我想知道如何追加一個換行符,每次列表達到棋盤(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) 

回答

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) 
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 
2

使用

if row_index % 8 == 0: 
    # put newline 
0

你的意思是你想每行之後追加新行? 爲什麼不加

pieceRow.append("\n") 

pieceList.append(pieceRow) 
0

你可以使用枚舉,

例如, CONST_SIZE = 8

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

每次將8個項目寫入文件時,這會附加一個換行符。