Create a file at ease

Image result for python open file

One of the most annoying thing it to me to write this code

import os
with open(filename, "w", encoding="utf-8") as file:
    file.write(content)
# This is to open the file created
os.system(filename)

Just to create a new file and write the content in it. So I decided to create a module just for that called createfile.

import os

def creafile(filename, content):
	"Create a file"
	try:
		with open(filename, "w", encoding="utf-8") as file:
			file.write(content)
		os.system(filename)
	except:
		print("You must use an argument for the filename ('prova.html') and another for the content ('<b>Hello</b> World')")

if __name__ == "__main__":
	creafile("filediprova.html", "<b>Hello</b>World")

So now, when I want to create a file with something in it and see immediately, I just write this code

from createfile import createfile

createfile("myfile.html", "<b>Hello</b> World")

So, with one line, I create the file, save it with the content and open it to see it. I like it, what do you think. Is it worthwhile, or it is better to write everytime alle that boring code?

https://pythonprogramming.altervista.org/how-to-create-a-list-of-tuple-from-a-string-pythonically/

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.