0

I can save file to utf-16-le, but i dont understand how save with bom it.

import csv

with open('filename.csv', mode='a', newline='', encoding='utf-16-le') as employee_file:
    writer = csv.writer(employee_file, delimiter=";")
    row = ['Job1', 'M']
    writer.writerow(row)

I can add '\ufeff to start of file, but i search alternative variant

mzjn
  • 48,958
  • 13
  • 128
  • 248
Ahvah
  • 1
  • 1
  • 4
    Why do you need to add a BOM? If the encoding of the file is declared to be `utf-16-le`, then there should be no BOM. See https://www.unicode.org/faq/utf_bom.html#bom9 ("if a text data stream is marked as UTF-16BE, UTF-16LE, UTF-32BE or UTF-32LE, a BOM is neither necessary nor permitted"). – mzjn Sep 14 '19 at 10:02
  • 1
    You may use just `utf-16`, which will put the BOM (but no guarantee that it is LE). On your case, it is also more tricky: you have mode `a`, and in theory code should ignore if the file it is at beginning or in the middle (where BOM) are not allowed. – Giacomo Catenazzi Sep 17 '19 at 12:01

1 Answers1

-1
def addUTF8Bom(filename):
  f = codecs.open(filename, 'r', 'utf-16-le')
  content = f.read()
  f.close()
  f2 = codecs.open(filename, 'w', 'utf-16-le')
  f2.write(u'\ufeff')
  f2.write(content)
  f2.close()
user1088259
  • 345
  • 13
  • 34
  • 3
    1) Please don't post an answer with only code and no explanatory text. 2) What are your reasons for breaking the guidelines from the Unicode consortium (see link in comment on the question)? 3) The OP already said "I can add `'\ufeff` to start of file". – mzjn Sep 14 '19 at 12:00