Python (Scripting) - Create a file using touch

by
Jeremy Canfield |
Updated: November 08 2024
| Python (Scripting) articles
open can be used to open a file for reading or writing. In the "open" statement, the second parameter can be:
- a = append to the file
- r = read the file
- w = write (overwrite) to the file
If the file does not exist and "a" (append) or "w" (write) are used, the file will be created. If "r" is used or no operand is used, and the file does not exist, "No such file or directory" will probably be returned so you may want to first use touch to create the file if it does not exist.
#!/usr/bin/python3
from pathlib import Path
Path("/tmp/foo.txt").touch()
Did you find this article helpful?
If so, consider buying me a coffee over at