Writing to a file is simple you open the file using either “a” or “w” and then use write() method to add content.
- “a”- Append content to an existing file.
- “w”- write to a file. This will override existing content.
Let’s see an example
f = open("hello.txt", "w") f.write("Hello universe!") f.close()
It will create a hello.txt file and write “hello universe!” content to it.
Let’s see another example using “a” mode in open() method:
f = open("hello.txt", "a") f.write("Append to existing content") f.close()
Output: This will add content to existing content without overriding it.
Creating a file.
Creating a file is simple if the file does not exist, open it using following mode
“a” – creates a file if the file does not exist. If the file already exist it will not throw an error.
“w”- creates a file if the file does not exist. If the file already exist it will not throw an error.
“x”- creates a file if the file does not exist. If the file exist it will throw an error.
f = open("hello_universe.txt", "a") f.write("Universe is awesome!") f.close()
It will create a file and add content to it.
Deleting a file.
You can delete a file using os module in python. In os module you can use remove(filepath) method to remove a file. It’s always a good idea to check if the file exist and then remove it. You can use os.path.exists(filepath) statement to check if the file exist.
Deleting a file
import os os.remove('hello_universe.txt')
Deleting a file after checking if file exist.
import os file_name = 'hello.txt' if os.path.exists(file_name): os.remove(file_name)