-1

My code


with open('text.txt') as f:
    text = f.read()

My Problem


Error

IDK what is that, this project is one of the first my projects, that work with files. Pls help me.

Kakiro
  • 1
  • pls add the text inside the text file you trying to read – Bhargav - Retarded Skills Aug 11 '22 at 15:05
  • 1
    Does this answer your question? [UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to ](https://stackoverflow.com/questions/9233027/unicodedecodeerror-charmap-codec-cant-decode-byte-x-in-position-y-character) – wovano Aug 11 '22 at 15:05
  • 1
    Did you already search for an answer here? This has been asked and answered many times already. To give a short summary: when opening a file, you could choose between binary and text format. If you choose text format, you should specify how the text is encoded. If you don't specify anything, [`open()`](https://docs.python.org/3/library/functions.html#open) will choose text mode for you, and your platform-dependent encoding is used (which seems to be cp1251 in your case, most likely Windows in a European country). Apparently the default don't work for you. So make them explicit to fix this. – wovano Aug 11 '22 at 15:08
  • By the way, please [do not upload images of code/errors](//meta.stackoverflow.com/a/285557/10669875). Instead copy-paste the error in the question. – wovano Aug 11 '22 at 15:09

1 Answers1

-1

Try specifying an encoding type for the file such as:

with open('text.txt', encoding = 'utf-8') as f:
    text = f.read()
DrHakeshi
  • 1
  • 2
  • Wow, it's okay now. But there is another UnicodeDecodeError, Traceback (most recent call last): File "c:\Users\kauba\Documents\projects\mine.py", line 25, in fi.write(lines[line] + "\n") File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1776.0_x64__qbz5n2kfra8p0\lib\encodings\cp1251.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 11-12: character maps to – Kakiro Aug 11 '22 at 15:18
  • Did you open the file for write and provide the encoding as utf-8 as well? – DrHakeshi Aug 11 '22 at 15:22
  • No, because if I do that, it will return another error: "io.UnsupportedOperation: not writable" – Kakiro Aug 11 '22 at 15:26