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.

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')

#Second method

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

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


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

Similar Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.