top of page
noun-documents-6053340-FFFFFF.png

Python 10a - Open & Write To Files

Creating and Opening Files

The "a" opens the file in append mode which will add new data to the end of the file.

The open command is used to open files but it is also used to create new files.

py208.PNG

'file' is just a variable and can be more relevant such as customer_file or whatever your file will be storing.

Python looks in the same folder as your .py file and checks to see if Customers.txt already exists.

​

If it doesn't exist, it will create the file.

The .txt extension will create a Notepad file. You can use alternatives such as .text or .docs.

Writing to a File

In the example below I ask the user to input a name which is written to the Names.txt file.

​

The .write command writes the contents of the brackets to the file.

​

You must close the file with the .close() command or the contents will not be saved.

py209.PNG
py210.PNG

The .write command can be adapted depending on how you want the file to appear:

py209.PNG
py213.PNG
py215.PNG
py211.PNG
py212.PNG
py214.PNG

Your text file won't update while it is open.

​

Close it and open it again to see any changes.

​

If you make any mistakes, just edit the file by hand and save it again.

Practice Task 1

Create a new file called MyFriends.txt

​

Ask the user to enter 5 names.

​

Write the 5 names into a file. Place each name on a separate line.

​

Check the file to see if the names have been entered.

Example solution:

py181.PNG

Writing Multiple Lines to a File

Files are often used to store data about multiple people.

​

The program below asks for a customer's name, appointment date and VIP status then saves this information into a file.

​

The plus symbol is used to write information for a single customer on the same line

​

This is beneficial if you want to search for a customer later.

py216.PNG
py217.PNG

Practice Task 2

Create a new file called ALevels.txt

​

Ask the user to enter a student's name and their three A-Level subjects.

​

Write each student's information on the same line.

 

Enter at least three different students and check your file to see it has worked.

Example solution:

py218.PNG
py219.PNG
bottom of page