2014-11-23 21 views
1

我有這是越來越線一些Python代碼結局都是錯誤的:蟒蛇的FileInput行尾

command = 'svn cat -r {} "{}{}"'.format(svn_revision, svn_repo, svn_filename) 
content = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read() 

written = False 
for line in fileinput.input(out_filename, inplace=1): 
     if line.startswith("INPUT_TAG") and not written: 
      print content 
      written = True 
     print line, 

這將提取稱爲svn_filename該文件的副本,並插入到內容在被叫out_filename另一個文件文件中的「INPUT_TAG」位置。

問題是out_filename中的行結束符。 它們的意思是\ r \ n,但我插入的塊是\ r \ r \ n。

更改打印語句:

print content, # just removes the newlines after the content block 

print content.replace('\r\r','\r') # no change 

沒有效果。內容離開我的代碼後插入額外的回車符。似乎有些事情正在決定,因爲我在Windows上應該將所有\ n轉換爲\ r \ n。

我該如何解決這個問題?

+0

您是否嘗試過使用'rstrip( '\ r \ n')'代替? – Carlos 2014-11-23 20:08:52

+0

只是嘗試打印content.rstrip('\ r \ n')並且沒有變化 – Daniel 2014-11-23 20:15:16

回答

0

CRLF =回車換行。

Windows上的Python區分了文本和二進制文件; 當讀取或寫入數據時,文本文件中的行尾字符會自動更改爲 。

https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

你能輸出二進制文件,而不是作爲一個文本文件?

如果你在字符串前加r到open the file as raw,這是否會阻止輸出中的額外\ r?

+0

for line in fileinput.input(filename,inplace = 1,mode ='rb'):奇怪讓事情變得更糟。不僅如此,文件的其餘部分現在也包含它們(不僅僅是插入的部分) – Daniel 2014-11-23 22:12:59

0

我可以做下面的「解決」這個問題:

content = content.replace('\r\n', '\n') 

轉換換行符到UNIX風格,所以當內部魔術再次將其轉換它結束了是正確的。

這不可能是正確的/最佳/ Python的方式,雖然....