Understanding the encoding Argument for the open Function in Python

Asked 2 years ago, Updated 2 years ago, 148 views

I tried to write the following code and write the data to the file, but I got the following error...
How can I modify the code below to write text data to a file simply...? I would appreciate it if you could let me know.(By the way, my python was python2...)

Code

with open(text_file, 'w', encoding="utf-8") asfp:#Where the error occurs
                    fp.write(text)

Error

Traceback (most recent call last):
  File "ExtractText.py", line 36, in <module>
    with open(text_file, 'w', encoding="utf-8") asfp:
TypeError: 'encoding' is an invalid keyword argument for this function

By the way, if you erase the encoding argument, you get the following error...

Code

with open(text_file, 'w') asfp:# Where the error occurs
                fp.write(text)

Error

Traceback (most recent call last):
  File "ExtractText.py", line 37, in <module>
    fp.write(text)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-10:ordinal not in range (128)

python text-file python2 encoding

2022-09-30 17:43

2 Answers

When writing, not when reading.

fp.write(text)

You may be experiencing an error in .

for.write(text.encode("utf-8")))

Can't you?


2022-09-30 17:43

I wonder if the encoding of the platform is different.
If you try encoding="shift_jis", you may be able to do it


2022-09-30 17:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.