-2

I want to use BOM with UTF-8. But it only saves files in UTF-8. What can I do ?I'm rather new, could you please write an answer as an addition to the sample code I shared directly?

import os
import codecs
a=1

filelist=os.listdir("name")
for file in filelist:
    filelen=len(os.listdir("name/"+file))
    if filelen==10:
        with open(file + ".iadx", "w", encoding="UTF-8") as f:
            f.write("<name>")
            f.write("\n")
            f.write('something')

Progman
  • 16,827
  • 6
  • 33
  • 48
  • Why do you need a BOM in UTF-8? It's not required or recommended. – Progman Dec 18 '22 at 21:38
  • 1
    Does this answer your question? [Write to UTF-8 file in Python](https://stackoverflow.com/questions/934160/write-to-utf-8-file-in-python) – Progman Dec 18 '22 at 21:41

1 Answers1

0

From Python documentation on codecs (search for "-sig") :

On encoding the utf-8-sig codec will write 0xef, 0xbb, 0xbf as the first three bytes to the file.

So just doing :

with open(file + ".iadx", "w", encoding="utf-8-sig") as f:
#                                             ^^^^

will do the trick.

Lenormju
  • 4,078
  • 2
  • 8
  • 22