0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to do it this way.

with open("foo.csv", "w" newline='', encoding='utf-8') as my_empty_csv:
    // other logic

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.