为什么我在写入文件时得到不必要的换行符?

我有一个从哪里读取一些数据的Excel文件,并基于一些逻辑,除了一些额外的数据之外,我还将excel文件的内容写入一个单独的文件。 我已经完成了除了这个不必要的换行符之外的所有事情。

我的程序:

from xlrd import open_workbook def create_script(): exl_file = open_workbook('DATA_SHEET.xls') data_sheet = exl_file.sheet_by_index(0) script_file.write("#Setting Inputs to FALSE values" + '\n\n') for row_idx in range(1, data_sheet.nrows): for col_idx in range(1): data_type = data_sheet.cell(row_idx,col_idx).value cell_text = data_sheet.cell(row_idx,col_idx+2).value if (data_type == 'Boolean'): if ('TRUE' not in cell_text) and (',' not in cell_text): book.seek(0) for line in book: if('%' in line): page_name = line if(cell_text in line): for src, target in replacement.iteritems(): page_name = page_name.replace(src, target) cmd = "SET 'ABC." + page_name + ".IO_" + cell_text + "' [ FALSE ]" + "\n" script_file.write(cmd) break; replacement = {'%':'', ':modifiable':''} script_file = open('script.txt', 'w') book = open('lookupfile.txt', 'r') create_script() script_file.close() book.close() 

我得到的实际输出:

 #Setting Inputs to FALSE values SET 'ABC.Page_1 .IO_Variable_1' [ FALSE ] SET 'ABC.Page_2 .IO_Variable_2' [ FALSE ] SET 'ABC.Page_3 .IO_Variable_3' [ FALSE ] SET 'ABC.Page_4 .IO_Variable_4' [ FALSE ] 

预期产出:

 #Setting Inputs to FALSE values SET 'ABC.Page_1.IO_Variable_1' [ FALSE ] SET 'ABC.Page_2.IO_Variable_2' [ FALSE ] SET 'ABC.Page_3.IO_Variable_3' [ FALSE ] SET 'ABC.Page_4.IO_Variable_4' [ FALSE ] 

正如你所看到的,我在Page_1,Page_2等等之后得到了换行符。 我相信这一行有一些问题,但不能找出确切的原因。

 cmd = "SET 'ABC." + page_name + ".IO_" + cell_text + "' [ FALSE ]" + "\n" 

这里可能是什么问题?

你必须有一个尾随的换行符:

 page_name.rstrip() 

所以cmd应该是这样的:

  cmd = "SET 'ABC.{}.IO_{}' [ FALSE ]\n".format(page_name.rstrip(),cell_text)