【发布时间】: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