Writing and Creating Files in Python
Â
In this tutorial we are going to learn:
- Writing Text Files
- Creating a New File
- Delete File
Â
Â
Writing Text Files
Â
To write a file, we have to open the existing file with the open() method and we must add a parameter to the open () function :
- ” a “  : Append – will append to the end of the file.
- ” w “  : Write – will overwrite the content.
Â
Example :
- Writing to a file with ” a “

Â
Output Of The Program :Â

Â
Â
Example :
- Writing to a file with ” w ” .

Output Of The Program :
We overwrote all content.

Â
Â
Â
Â
Creating a New File
Â
To create a new file we use the open() method and we must add a parameter ” x “ as a mode to our open() function.
Example :Â

Â
Output Of The Program :Â
As you can see our new “newfile.txt” file created.

Â
Â
Â
Delete File
Â
To delete a file, we use os.remove() method.
Â
Example :

Â
Output Of The Program :Â
As you can see our “newfile.txt” was deleted.

