[英]Appending a new line to file
我想知道每次列表達到棋盤大小(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)
采用
if row_index % 8 == 0:
# put newline
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)
cnt = 0
for item in pieceList:
for char in item:
outputFile.write("%s" %char)
cnt += 1
if cnt == 8:
outputFile.write("\n")
cnt = 0
您是說要在每行后添加換行符嗎? 為什么不添加
pieceRow.append("\n")
之前
pieceList.append(pieceRow)
您可以使用枚舉,
例如,CONST_SIZE = 8
for index, item in enumerate(item_list):
output_file.write(item)
if index % 8 == 0: output_file.write('\n')
每次將8個項目寫入文件時,都會在該行之后添加換行符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.