0

my .txt file is below

Pyhton is open source language
its a freeware
it has lot of in built modules
python is easiest

what should I do to insert two lines below its freeware lines and move the remaining data below that inserted lines, as shown below,

Pyhton is open source language
its a freeware
Hi
my name is shubham
it has lot of in bult modules
python is easiest

I have tried following code but its appending the new lines at last in file

file_to_write = r"file.txt"
with open(file_to_write,'a') as fw:
    fw.write('Hi\n')
    fw.write('my name is shubham')

1 Answers1

1

In order to make a new line add \n before where you wish to add a new line within the string.

\n = move to next line, so if you need to move it down further just add more \n, for example:

\n\n = move 2 lines below.

EXAMPLE.

text = "Python is an open source language. \nits a freeware \n\nHi my name is shubham. it has lot of in built modules python is easiest"

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

Notice how i have enclosed all the text in one variable, and whereever I needed to insert a new line (or several new lines), I have included, 1 or more \n before the text.

Now that all the info is stored within the single variable text, I am now able to simply pass the text variable as a parameter for the write function and have it all appropriately save in the test.txt file.

SShah
  • 1,044
  • 8
  • 19
  • as you said '\n' adds new line yes, but i need to insert new two lines in between file not at the end of file like append – shubham008 Feb 26 '18 at 11:05
  • I have edited my answer to include an example, please let me know if that is the solution you seek. Sorry if I am misunderstanding what you want to do. – SShah Feb 26 '18 at 11:53