0

I need to add a line break to every single line of text

I have changed a CSV file to a text file, in that text file I need to add a line break at the end of every line/sentance

I can only manage currently to add a single line break on the first line of text, I can not work out how to do it for subsequent lines

An example of what I have when I change the CSV file to Txt:

Device_1 A 10.0.0.1
Device_2 A 10.0.0.2
Device_3 A 10.0.0.3

An example of what I want it to look like

Device_1 A 10.0.0.1

Device_2 A 10.0.0.2

Device_3 A 10.0.0.3

An example of what it actually looks like after the python script runs

Device_1 A 10.0.0.1

Device_2 A 10.0.0.2
Device_3 A 10.0.0.3

The code I have tried:

import shutil

source = 'DNS_Entries.csv'
target = 'DNS_Entries_Copy.txt'

shutil.copy(source, target)

def DNS_Entries(self,DNS):
    with open(DNS) as f:
        lines = [line+'\n' for line in f.readlines()]

    with open(DNS+'DNS_Entries_Copy.txt', 'w') as f:
            f.write(''.join(lines))

I have also tried:

import shutil

source = 'DNS_Entries.csv'
target = 'DNS_Entries_Copy.txt'

shutil.copy(source, target)

def DNS_Entries(self,DNS):
    with open(DNS) as f:
        lines = [line+'\n' for line in f.readlines()]

    with open(DNS) as source:
        with open(DNS+'DNS_Entries_Copy.txt', 'w') as output:
            for line in source:
                f.write(line+'\n')

Both of the above scripts add a single line break at the end of the first line of text.

Unfortunately its never the same number or character at the end of the line to reference and each line can differ with the amount of characters/numbers per line.

Thanks

1
  • The first code works perfectly fine for me... Commented Nov 21, 2022 at 12:42

1 Answer 1

1

Sounds like a job for regex:

text = """Device_1 A 10.0.0.1
Device_2 A 10.0.0.2
Device_3 A 10.0.0.3"""

import re
print(re.sub("\n", "\n\n", text))

Be warned: as a famous rapper once almost sang, I got 99 problems and then I tried to use regex on one of them and now I have 100.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.