在python 2.7.15中有条件地替换行尾

时间:2018-06-29 20:26:56

标签: python python-2.7 tortoisesvn line-endings cornerstone

我有一些svn补丁,不幸的是它们的行尾混合在一起。我的Windows svn客户端(草龟)使用CRLF行尾保存其元数据。但是,我的同事在MacOS上使用Cornerstone来应用需要元数据才能具有LF行尾的补丁。我无法批量更改文件中的所有行尾(通过管理来解决)。我只需要更改元数据的行尾。

我能够在补丁文件中检测到CRLF行尾,但是尝试用LF替换行不通。有人可以帮忙吗?如果有更有效的方法,请告诉我。

我正在使用python 2.7.15

import sys
import os

CRLF = '\r\n'
LF = '\n'

filePath = sys.argv[1] 
newFilePath = filePath.replace('.patch', '-converted.patch')

newFile = open(newFilePath,'wb')
oldFile = open(filePath, 'r+b')

for idx,line in enumerate(oldFile.readlines()):
        line = str(line)
        if line.startswith("=====") or line.startswith("@@") or line.startswith("+++") or line.startswith("---") or line.startswith("Index:"):
                if line.endswith(CRLF):
                        print ("detected CRLF at line " + str(idx))
                        line.replace(CRLF, LF)
                        print ("converted line ending to LF at line " + str(idx))
                        if line.endswith(CRLF):
                                print("hmm... line " + str(idx) + " still a crlf line!!!!!!!!")
        newFile.writelines(line)

oldFile.close()
newFile.close()

1 个答案:

答案 0 :(得分:2)

replace方法不会更新从其调用的对象,而只是将替换后的字符串作为返回值返回,因此您需要将返回值分配回变量以对其进行更新。

更改此行:

line.replace(CRLF, LF)

收件人:

line = line.replace(CRLF, LF)
相关问题