Introduction
The very basics of text files
4. Writing to a file
with statement and exception handling
Summary

Instruction

Good! Now, let's see how we can use another mode – 'w' (write) – to create a new file and store some information inside it.

firstname = input('What is your first name? ')
lastname = input('What is your last name? ')

file = open('user_data.txt', 'w')
file.write(firstname + '\n')
file.write(lastname)
file.close()

First, we ask the user for their first and last name. Then, we open a file in the 'w' mode. This means that Python will create a new file named 'user_data.txt', or will overwrite an existing file with that name. Next, we use file.write() to write some text into that file. Note that you need to use '\n' to get a newline character. Finally, we close the file as before.

Exercise

Ask the user for their nickname and age. Next, open a file named user_data.txt in write mode ('w'), and put the following two lines inside it:

Nickname: {nickname}
Age: {age}

Close the file afterwards.