Exercise 56

Given a file called myfile.txt which contains the following lines:

line 1
line 2
line 3

write a Python program that transforms the content into the form:

line 3
this line has just been inserted via Python code
line 2
line 1

Solution


# creating and opening file in write mode
f = open('myfile.txt' , 'r')

# getting the file content
content = f.read()
f.close()

# converting the content to a list
L = content.split()

# swap the line 1 with the line 3
swap = L[0]
L[0] = L[2]
L[2] = swap

# Insert new line
L.insert(1, "this line has just been inserted via Python code")

# opening myfile.txt in write mode by overwriting its content.
f = open('myfile.txt' , 'w')

# building file content
for line in L:
f.write(line + 'n')

f.close()
Younes Derfoufi
my-courses.net

Leave a Reply