Creating a new file
The open command is used to open files but it is also used to create new files.
Look at the following code:
Python will look in the same folder that you have saved this Python document (such as My Documents) for a file called Bookings.txt. If it can’t find a file with this exact name then it creates it.
The ‘wt’ stands for ‘write to’ and means you want to open the file in ‘write mode’ to edit its contents.
‘File’ is the variable name and can be called whatever you like.
Opening an existing file
To open an existing file you need to make sure it it is saved in the same folder as your Python document (it should automatically be if you created it in Python like above). Make sure that you spell it right and use the correct extension (such as .txt or .text or .doc)
Writing to a File
After you have opened or created a file in write mode you can start saving data into it. A simple method of writing one line at a time is below:
If you want to write on different lines then you will need to use the n command that we looked at all the way back in section 1:
This is okay for small amounts of data but you may well want to use a list to hold more. We can use a list to write each item in the list to the file:
In the example above the second write line is used to create a new line for each piece of data, which makes it much clearer when outputted later:
Closing a file
Easy as pie, you just need to write .close() after your file variable, like: