繁体   English   中英

更换回车 (CR) 和回车换行 (CRLF) python

[英]Replace Carriage Return (CR) and Carriage Return and Line Feed (CRLF) python

我导入了一个.csv文件,如下所示:

在此处输入图像描述

通过使用以下代码

filetoread = 'G:/input.csv'
filetowrite = 'G:/output.csv'

# https://stackoverflow.com/questions/17658055/how-can-i-remove-carriage-return-from-a-text-file-with-python/42442131

with open(filetoread, "rb") as inf:
    with open(filetowrite, "wb") as fixed:
        for line in inf:
            # line = line.replace('\r\r\n', 'r\n')
            fixed.write(line)
            print(line)

其中给出了 output:

b'\xef\xbb\xbfHeader1;Header2;Header3;Header4;Header5;Header6;Header7;Header8;Header9;Header10;Header11;Header12\r\n'
b';;;1999-01-01;;;01;;;;;;\r\n'
b';;;2000-01-01;;;12;;"NY123456789\r\r\n'
b'";chapter;2020-01-01 00:00:00;PE\r\n'
b';;;2020-01-01;;;45;;"NY123456789\r\r\n'
b'";chapter;1900-01-01 00:00:00;PE\r\n'
b';;;1999-01-01;;;98;;;;;;\r\n'

我有问题要将\r\r\n替换为\r\n ,我想我需要这样做才能获得我想要的 output。 我尝试替换\r\r\n时遇到的错误是:

Traceback (most recent call last):
  File "g:/till_format_2.py", line 10, in <module>
    line = line.replace('\r\r\n', 'r\n')
TypeError: a bytes-like object is required, not 'str'

我想要的 output:

在此处输入图像描述

我需要添加或更改代码以实现我想要的 output?

如错误消息所述,提供bytes object。

line = line.replace(b'\r\r\n', b'\r\n')

得到想要的 output

line = line.replace(b'\r\r\n', b'')

暂无
暂无

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

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