1. Opening a file
2. Write

Successful execution

Error message

UnicodeEncodeError:'cp932'codec can't encode charactaer'\ xa5'in positition5: illegal multibyte sequence

Applicable source code
f = open ("Sample.txt", "w")
f.write ( "Hello ¥ n")
f.write ("Goodbye \ n")
f.close ()
f = open ("Sample.txt", "w")
f.write ( "Hello")
f.write ("Goodbye")
f.close ()
Supplemental information (FW/tool version etc.) If

\ n is not used, no error will occur.
How should we deal with it?

  • Answer # 1

    You entered the wrong\. Please enter a half-width backslash. Or copy and paste \.

  • Answer # 2

    \and\may appear the same, but they are different characters.
    Try copying the following code.

    f = open ("Sample.txt", "w")
    f.write ( "Hello \ n")
    f.write ("Goodbye \ n")
    f.close ()

    I think this will work.

  • Answer # 3

    Do you want to use python2?
    Add #-*-coding: utf-8-*-at the top of the program
    please look.
    (If you are creating a file with shift_jis, specify shift_jis instead of utf-8.

    Reference information

    How to handle Japanese in Python