2016-10-04 23 views
-1

目前我有这样的代码:最好使用join或append?

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

您不能使用附加字符串。只需简单地在使用'+'加入后添加换行符。 –

回答

1

只需添加一个+ "\n"到最后,是这样的。

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

这将在加入后添加一个新行。

+0

非常感谢你!我甚至不知道我可以做到这一点 – user6923100

+0

欢迎您。如果你想了解更多关于python字符串的信息,请看[Python Strings Tutorials Point](https://www.tutorialspoint.com/python/python_strings.htm) –