繁体   English   中英

替换 \n 同时保持 \r\n 不变

[英]Replacing \n while keeping \r\n intact

我有一个巨大的 CSV 文件(196244 行),其中除了新行之外还有 \n,我想删除那些 \n 但保持 \r\n 完好无损。 我已经尝试过line.replace但似乎无法识别\r\n所以接下来我尝试了正则表达式

with open(filetoread, "r") as inf:
    with open(filetowrite, "w") as fixed:
        for line in inf:
            line = re.sub("(?<!\r)\n", " ", line)
            fixed.write(line)

但它并没有保留\r\n它正在删除所有内容。 我不能在 Notepad++ 中执行此操作,它会在此文件上崩溃。

您没有将换行符暴露给正则表达式引擎。 此外,当使用r模式open时,换行符被“规范化”为 LF,为了将它们全部保留在输入中,您可以使用b以二进制模式读取文件。 然后,您还需要记住在正则表达式模式和替换中使用b前缀。

您可以使用

with open(filetoread, "rb") as inf:
    with open(filetowrite, "wb") as fixed:
        fixed.write(re.sub(b"(?<!\r)\n", b" ", inf.read()))

现在,整个文件将被读入单个字符串(使用inf.read() )并且换行符将被匹配,并最终被替换。

关注

  • 读取文件时的"rb"
  • "wb"写出文件
  • re.sub(b"(?<,\r)\n", b" ". inf.read())包含带有字符串文字的b前缀,并且inf.read()将文件内容读入单个变量。

当您使用一个简单的open()调用打开一个文件时,它将通过TextIOWrapper加载一个包含各种换行符的文件视图,只需\n

显式设置newline="\r\n"应该允许您按照预期的方式读写换行符

with open(path_src, newline="\r\n") as fh_src:
    with open(path_dest, "w", newline="\r\n") as fh_dest:
        for line in fh_src:  # file-likes are iterable by-lines
            fh_dest.write(line[:-2].replace("\n", " "))
            fh_dest.write("\r\n")

内容示例

>>> with open("test.data", "wb") as fh:
...     fh.write(b"""foo\nbar\r\nbaz\r\n""")
...
14
>>> with open("test.data", newline="\r\n") as fh:
...     for line in fh:
...         print(repr(line))
...
'foo\nbar\r\n'
'baz\r\n'

暂无
暂无

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

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