Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split with empty line delimiter

Tags:

python

I'm having trouble splitting a text file using empty line "\n\n" delimiters.

re.split("\n", aString) 

works but

re.split("\n\n", aString) 

just returns the whole string.

Any ideas?

like image 862
Bertiewo Avatar asked Feb 16 '26 16:02

Bertiewo


1 Answers

Beware the line ending conventions of different operating systems!

  • Windows: CRLF (\r\n)
  • Linux and other Unices: LF (\n)
  • Old Mac: CR (\r)

You are probably failing because the double newline you are looking for is in a Windows-encoded text file, and will appear as \r\n\r\n, not \n\n.

The repr() function will tell you for sure what your line endings are:

>>> mystring = #[[a line of your file]]
>>> repr(mystring)
"'\\nmulti\\nline\\nstring '"

Are you sure that you don't just want to read the file line by line in the first place?

with open(file.txt, 'r') as f:
    for line in f:
        print (line)
like image 58
Li-aung Yip Avatar answered Feb 19 '26 06:02

Li-aung Yip