Exercise 53

Create manually  two files in the same directory:

  • python_code.py
  • myfile.txt

1) - Create a Python program that writes the following three lines to the myfile.txt file:
First line
second line
third line
2) - Write a Python program on python_code.py that  replace the second line with the line:  "sorry! The content of this line has been changed! "

Solution 

Question1


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

# creating a lines content
lines = ["first linen" , "second linen" , "third linen"]

# writing lines on myfile.txt
f.writelines(lines)
f.close()

Question2


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

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

# changing the second line
linesContent[1] = "sorry! The content of this line has been changed!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
One thought on “Solution Exercise 53: python code to write and edit file”

Leave a Reply