Exercice 54:

Write a program in Python which allows you to insert at the 3rd position of an existing file called myFile.txt, the line "This line was inserted via Python code! " without changing the existing content file.

Solution

# opening file in read mode
f = open("myFile.txt" , "r+")

# getting content lines
linesContent = f.readlines()
f.close()

# Inserting a line at third position
linesContent.insert(2 , "This line was inserted via Python code!n")

# opening file in write mode
f = open("myfile.txt" , "w")

#writing new lines content
f.writelines(linesContent)
f.close()
Younes Derfoufi
my-courses.net

Leave a Reply