2014-11-23 53 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的方式,虽然....