## Wednesday, September 16, 2020

Solution Exrcise 62: creating a file and writing lines on it with Python

#### Exercise 62

a)Write a python program that create a text file called myFile.txt and write on it the following lines:

- this is the line 1

- thtis is the line 2

- this is the line3

- this is the line4

- this is the line5

- this is the line6

- this is the line7

- this is the line8

- this is the line9

- this is the line10

b) Write a Python program which allows you to read the first 5 lines of myFile.txt.
c) Write a program to read the last 5 lines of myFile.txt
d) Write a Python program which allows you to extract the content of a file from the 3rd line to the 7th line and save it in another file called extract_content.txt.

### Question a)

``````# opening new file called myFile.txt in write mod
file = open("myFile.txt" , 'w')
# create the list of lines
listLines = ['- this is the line1' , '- this is the line2' , '- this is the line3' ,
'- this is the line4' , '- this is the line5' ,'- this is the line6' ,
'- this is the line7' , '- this is the line8' , '- this is the line9' ,
'- this is the line10' ]

# write all line on opened file
for line in listLines:
file.write(line + "\n")
file.close()
``````

This will be create a file called myFile.txt:

### Question b)

``````# opening myFile.txt in read mod
file =open("myFile.txt" , 'r')

# getting list of all contnent lines

# print the 5 first lines
for i in range(0 , 5):
print(lines[i])``````

The output is:

- this is the line1

- this is the line2

- this is the line3

- this is the line4

- this is the line5

### Question d)

même méthode que la question précédente en appliquant la boucle de i = 2 juqu'à i = 7
``for i in range(0 , 5):``

Younes Derfoufi
my-courses.net