2016-10-04 6 views
-1

В настоящее время у меня есть этот код:Лучше всего использовать соединение или добавить?

with open(w_file, 'r') as file_r: 
    for line in file_r: 
     if len(line) > 0: 
      spLine = line.split() 
      if(spLine[0] == operandID and spLine[1] == bitID 
      and spLine[3] == sInstID and spLine[4] == opcodeID): 
       spLine[-2]='1' 
       line = ' '.join(spLine) # I need to add a new line into 
             # "line" after join all the spLine 
      lines.append(line) 
      print line 
with open(w_file, 'w') as file_w: 
    for line in lines: 
     file_w.write(line) 

Выход:

1 60 14039 470 13 0 28 
1 60 14039 470 13 0 28 
0 60 14039 470 13 1 281 60 14039 470 13 0 28 # I want to separate these two 
1 60 14039 470 13 0 28      # lines, this wrong situation 
               # only happens when I found 
               # the target line which 
               # satisfies the if statement. 
+0

Вы не можете использовать append со строкой. Просто добавьте новую строку после объединения с помощью '+'. –

ответ

1

Просто добавьте + "\n" до конца, как это.

line = ' '.join(spLine) + "\n" 

Это добавит новую линию после присоединения.

+0

Спасибо вам столько! Я даже не знаю, что смогу это сделать – user6923100

+0

Ваш прием. Если вы хотите узнать больше о строках python, [Python String Tutorials Point] (https://www.tutorialspoint.com/python/python_strings.htm) –

Смежные вопросы