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.
'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.
The .write command can be adapted depending on how you want the file to appear:
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.
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.
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.