r/PythonLearning • u/Correct_Ask_6824 • 4d ago
Help Request How to convert UTF-16 to UTF-8 in Macbook?
Hello, I wrote a code on my macbook that I have to transfer to a windows computer that is permanently offline. However, the windows computer python doesnt want to read the code because it has "null bytes" apparently it can't read UTF 16 only UTF 8. Is there a command I can run on my macbook terminal to change the .py file to UTF-8? Please let me know. Thank you!
3
Upvotes
1
u/copperbagel 4d ago
There is a python method to encode and decode
with open("input_utf16.txt", "r", encoding="utf-16") as source: content = source.read()
with open("output_utf8.txt", "w", encoding="utf-8") as target: target.write(content)
1
u/Due-Mortgage-6854 4d ago
Run this in your MacBook terminal :
iconv -f UTF-16 -t UTF-8 input.py > output.pyReplace input.py with your current UTF-16 file name Replace output.py with a new file name If UTF-16 gives an encoding error because the file lacks a byte-order mark, try UTF-16LE or UTF-16BE instead
1
u/fllthdcrb 23h ago
Not true. There are plenty of text encodings Python can work with. However, Python is not in the business of trying to guess what something is; it's a programming language, not an analyst. It assumes UTF-8 by default, because that's the most widely used, and is relatively compact for mostly roman text, while covering all of Unicode. But if something uses some other encoding, you either have to specify that, or convert it beforehand.