Q:

Creating a new csv with UTF-8 encoding

I have a process which requires a csv to be created if it does not currently exist. I then open this csv and write some data to it.
with open("foo.csv", "w") as my_empty_csv:
  # now you have an empty file already
  # This is where I write my data to the file

This is the code i'm currently using, but I don't know what default encoding the file is created in if it doesn't already exist.
What would be the better way to create a file with UTF-8 encoding if the file doesn't exist.

A:

The open function has an optional 'encoding' parameter that you can use to explicitly specify the encoding of the file:
with open("foo.csv", "w", encoding="utf-8") as my_empty_csv:
    ...

More specificially, the documentation specifies about this parameter:

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

