Python – Writing to a text file (Lesson 2)

If all went as it should have in the last task, the names in the text file should have appeared all in one line like the image below.

Picture1

 

Python has escape codes. The code \n should be able to help us put each name on a new line.

Where do you think we need to add this?

This can be done in two ways:

# First Method

file = open('textfile.txt', 'w')

file.write('name 1\n')
file.write('name 2\n')
file.write('name 3\n')
file.write('name 4\n')

file.close()

 

#Second method

file = open('textfile.txt', 'w')

file.write('name 1')
file.write('\n')
file.write('name 2')
file.write('\n')
file.write('name 3')
file.write('\n')
file.write('name 4')
file.write('\n')

file.close()

Task 2 Give it a try and see if it works.

Posted in Uncategorized.

Leave a Reply

Your email address will not be published. Required fields are marked *


*