Ad

How To Add Empty Lines Between Lines In Text.txt Document?

- 1 answer

The purpose of the code is to add an empty line between lines in text.txt document and write some words in those empty lines. I tried looping through every line but the file should be in read mode only;

iushnaufihsnuesa
fsuhadnfuisgadnfuigasdf
asfhasndfusaugdf
suhdfnciusgenfuigsaueifcas

This is a sample of text.txt document how can i implement this on this txt?

f = open("text.txt", 'w+')
for x in f:
f.write("\n Words between spacing")

f.close()

First i tried directly to just make a new line between each line and add couple of stuuf

I also thought of first making empty lines between each line and then add some words in the empty spaces but I didn't figure this out

Ad

Answer

Ok, for files in the region of 200 lines long you can store the whole file as a list of strings and add lines when re-writing the file:

with open("text.txt", 'r') as f:
    data = [line for line in f]

with open("text.txt", 'w') as f:
    for line in data:
        f.write(line)
        f.write("Words between spacing\n")
Ad
source: stackoverflow.com
Ad