Paties
Paties

Reputation: 47

How to add empty lines between lines in text.txt document?

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

Upvotes: 0

Views: 2062

Answers (2)

RrR2010
RrR2010

Reputation: 91

You can divide this operation in three steps. In the first one, you read all the lines from the file into a list[str] using f.readlines():

with open("text.txt", "r") as f: # using "read" mode
    lines = f.readlines()

Second is to join these lines inside the list using the "".join(...) function.

lines = "My line between the lines\n".join(lines)

On third step, write it down to the file:

with open("text.txt", "w") as f: # using "write" mode
    f.write(lines)

Also, you can use f.read() in conjunction with text.replace("\n", ...):

with open("text.txt", "r") as f:
    full_text = f.read()

full_text = full_text.replace("\n", "\nMy desirable text between the lines\n")

with open("text.txt", "w") as f:
    f.write(full_text)

Initial text:

iushnaufihsnuesa
fsuhadnfuisgadnfuigasdf
asfhasndfusaugdf
suhdfnciusgenfuigsaueifcas

Final text:

iushnaufihsnuesa
My desirable text between the lines
fsuhadnfuisgadnfuigasdf
My desirable text between the lines
asfhasndfusaugdf
My desirable text between the lines
suhdfnciusgenfuigsaueifcas

Upvotes: 1

quamrana
quamrana

Reputation: 39344

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")

Upvotes: 3

Related Questions