In this tutorial you will learn:
File Writing Modes
In Python we have the ‘w,’ ‘a’ and ‘+’ for writing to a file. For appending data to an already written file we use ‘a’
|w||For writing or creating a file.|
|a||For appending to a file.|
|+||For opening a file for reading or writing.|
File Writing in Python
We can write to new and existing files in Python. For writing we need to perform three main tasks one is to open the file, next one is to write the file and the last step is to close the file after writing.
We will use the ‘w’ mode for this example as the file is not created. We will create the file and write the data into it.
- f = open("myFile.txt", "w")
- f.write("Example of writing to a file")
Now in the next example we will append the data to our already created “myFile.txt”. For appending data we need to use the “a” mode.
- f = open("myFile.txt", "a")
- f.write("Example of appending to a file")
Deleting a File
To delete a file we need to import a module called OS which gives us a remove method to delete files.
- import os
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.
Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.
FOR YOUR OWN SAFETY, PLEASE:
1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.