繁体   English   中英

用一个字符替换一个字符(\\ n由\\ r \\ n取代)也会替换其中一个替换字符

[英]Replacing one character with two (\n by \r\n ) replaces also one of the replacing characters

我正在尝试使用此脚本将大量文件转换为公共行结尾。 使用for循环在git-shell中调用该脚本。

运行所有行结束后只有CR作为行结束。 我想因为替换(内容,'\\ n','\\ r \\ n')也会在\\ r \\ n之后替换\\ n。 是否有可能阻止它? 我应该替换linewise吗?

import sys
import string
import os.path

for file in sys.argv[1:]:
    if not os.path.exists(file):
        continue
    contents = open(file, 'rb').read()
    cont1 = string.replace(contents, '\n', '\r\n' )
    open(file, 'wb').write(cont1)

我尝试了你的代码字面上的复制粘贴,它在python2.7上运行得很好:

bash$ cat file1
one
two

bash$ file file1
file1: ASCII text

bash$ hd file1
00000000  6f 6e 65 0a 74 77 6f 0a                           |one.two.|
00000008

bash$ python2 lineend.py file1

bash$ hd file1
00000000  6f 6e 65 0d 0a 74 77 6f  0d 0a                    |one..two..|
0000000a

bash$ file file1
file1: ASCII text, with CRLF line terminators

但请注意,您要打开两次相同的文件:一次用于阅读,一次用于写入。 在这个确切的情况下可能不会引起问题,但通常这不是好的做法。

import sys
import string
import os.path

for file in sys.argv[1:]:
    if not os.path.exists(file):
        continue
    f = open(file, 'rb')
    contents = f.read()
    f.close()
    cont1 = string.replace(contents, '\n', '\r\n' )
    open(file, 'wb').write(cont1)

您可以使用re.sub执行正则表达式替换。

而不是这一行:

cont1 = string.replace(contents, '\n', '\r\n' )

您将使用以下行(不要忘记import re ):

cont1 = re.sub(r'([^\r])\n', r'\g<1>\r\n', contents)

更新:

r'([^\\r])\\n'与文件开头的换行符不匹配。 使用r'([^\\r])?\\n'代替应该完成这项工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM