2013-03-27 153 views
3

我想用python在每行的開頭和末尾添加一些字母。添加到Python的一行的末尾

我發現了這樣做的各種方法,但是,無論採用哪種方法,我使用我要添加到結尾的字母都始終添加到開頭。

input = open("input_file",'r') 
output = open("output_file",'w') 

for line in input: 
    newline = "A" + line + "B" 
    output.write(newline) 
input.close() 
output.close() 

我已經使用了我在這裏找到的varios方法。他們中的每一個都被添加到前面。

inserting characters at the start and end of a string

''.join(('L','yourstring','LL')) 

yourstring = "L%sLL" % yourstring 

yourstring = "L{0}LL".format(yourstring) 

我清楚地失去了一些東西。我能做什麼?

+0

您是否考慮過使用'sed',或者您是否使用python? 'sed'#$#LL'input_file | sed的#^#L#'> output_file'可能比python所做的更快。 – 2013-03-27 17:54:22

回答

7

從一個文件中讀取行時,python離開了\n。但是,您可以將.rstrip關閉。

yourstring = 'L{0}LL\n'.format(yourstring.rstrip('\n')) 
+0

啊!謝謝! – Constantin 2013-03-27 18:04:03