How to read in text lines containing ^M character in Python?

Viewed 39
时尚 娱乐明星 设计 家装家居 过节指南圣诞节穿搭^M 圣诞月怎么红红绿绿怎么来

I am reading in a text file like above:

with open('test.tsv', 'r', encoding='utf8') as f:

   for line in f:
      print(f)

Due to the ^M character, the line ends at this character, not the whole line. How to read the whole text as one single line instead of multiple lines? I can replace it with a space.

In vim, I tried Ctr+M on my mac to search it, but the search failed. How to either remove it in vim or in python code to replace it with a space?

1 Answers

use the below command to get rid of ^M in vim and to insert ^M Press Ctrl+V Ctrl+M

:s/^M$//

Instead of removing ^M if you want to replace ^M with newline use

:%s/^M/\r/g

For mac users use dos2unix command

dos2unix myfile.txt

without using Ctrl you can replace ^M using the below command:

:%s/\r$/ /g
Related