Execute python, on Linux to write newline characters in the file

  1. python is executed on Linux, version 2.7
  2. For the file operation in
  3. python, writing a newline character, the following error occurred:
Traceback (most recent call last):
  File "parse_new.py", line 130, in <module>
    main()
  File "parse_new.py", line 102, in main
    f.write("\n")
TypeError: must be unicode, not str
Sep.11,2021

try this


     f.write(u'\n') -sharp u  unicode

python2.7 does not have a default unicode encoding. Just convert it to unicode encoding. For example, print (upright ')


  1. when writing a string in a file, you can use: f.write (uplinn') u means to encode in Unicode
  2. python 2.7 does not have a default Unicode encoding, so you need to encode the elements yourself

  3. StrToUnicode using decode (); UnicodeToStr using encode ()
    example:
    with io.open('xxxx', 'a') as f:
        for i in LIST:
            f.write(i.decode('utf-8','ignore'))
            f.write(u"\n")

ps:

python3python3
Menu