Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python combine lines without blank new lines

Tags:

python

newline

i need your help with the following problem. I have some large textfiles for example:

This is the Name of the Person

This is his surname

He likes to sing 
every time.

I only want to merge the line He likes to sing with every time. because i do other regex stuff with each string after this.

So the output should be:

This is the Name of the Person

This is his surname

He likes to sing every time.

So ive tried it with:

for file in file_list:
    with open(file, 'r', encoding='UTF-8', errors='ignore') as f_in:
        for line in f_in:
              if not line.startswith('\n'):
                line.replace('\n', '')
                print(line)

Thanks for your help.

like image 200
Razziziz Avatar asked Dec 09 '25 17:12

Razziziz


1 Answers

You may try this:

for file in file_list:
    with open(file, 'r', encoding='UTF-8', errors='ignore') as f_in:
        lines = [i.replace('\n', ' ') for i in f_in.read().split('\n\n')]

    # here you do something with your `lines`
like image 200
lenik Avatar answered Dec 11 '25 06:12

lenik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!