【问题标题】:Replace Carriage Return (CR) and Carriage Return and Line Feed (CRLF) python替换回车 (CR) 和回车换行 (CRLF) python
【发布时间】:2020-07-13 19:33:09
【问题描述】:

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

通过使用以下code

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)

给出输出:

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 时遇到问题,我想我需要这样做才能获得所需的输出。 我尝试替换 \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'

我想要的输出:

我需要在代码中添加或更改什么来实现我想要的输出?

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

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

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

    得到想要的输出

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

    【讨论】:

      猜你喜欢
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 2014-12-11
      • 2020-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多