Bertiewo
Bertiewo

Reputation: 216

Split with empty line delimiter

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?

Upvotes: 3

Views: 13872

Answers (1)

Li-aung Yip
Li-aung Yip

Reputation: 12486

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)

Upvotes: 6

Related Questions