How to open a file or create a file withPython

Save a file in Python

We can save in a pythonic way a file with “with“, as in the code below. In the code we also used the module time to get the date of today and use it to add it to the name of the file. It is an html file, but it could have been a txt file, or any other file (depending on the content). The <h1> </h1> tags are from html and they mean that the word between them is a header, so it will be bigger than the normal text. The ‘w’ that you see in the arguments of open is for write, for this kind of ‘opening’ is to add things to the file. We added the content of the variable html, seen before. You can also use ‘a’ that is for append, if you want to add something to an existing file, without eracing what there was before in the file.

import time

# data contains the date of today
data = time.strftime("%d%m%Y")

# This variable contains a string with a text in html format
html = "<h1>This is a title</h1>

# Here I write/create a file called file + date of today with .html at the end
with open(f"file{data}.html", "w", encoding="utf-8") as file:
    file.write(html)

Open a file with python

To open a file, the code is almost identical. What changes is the ‘r’ that stands for read. This file, can only be read, not to be written. You must use ‘w’ as we’ve seen in the previous paragraph, above.

with open(f"compito{data}.html", "r", encoding="utf-8") as file:
    f = file.read()
    print(f)

 

 

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

Utilities

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.