Skip to content

mimetypes raises UnicodeDecodeError when map files are not unicode encoded #117807

Open

Description

@kulikjak

Bug report

Bug description:

Hi, when I use the mimetypes module and one of the known mime.types files include a non utf-8 encoded comment, the operation fails with UnicodeDecodeError:

......
  File "/usr/lib/python3.9/urllib/request.py", line 1506, in open_local_file
    mtype = mimetypes.guess_type(filename)[0]
  File "/usr/lib/python3.9/mimetypes.py", line 289, in guess_type
    init()
  File "/usr/lib/python3.9/mimetypes.py", line 362, in init
    db.read(file)
  File "/usr/lib/python3.9/mimetypes.py", line 204, in read
    self.readfp(fp, strict)
  File "/usr/lib/python3.9/mimetypes.py", line 215, in readfp
    line = fp.readline()
  File "/usr/lib/python3.9/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x83 in position 168: invalid start byte

The same can be forced with:

import mimetypes
mimetypes.init(files=["mimefile"]) 

and occurs because the file is opened in text mode expecting unicode encoding:

with open(filename, encoding='utf-8') as fp:

I am not sure whether there is a convention for which encoding the mime.types file will use, but I feel that at least comments should be allowed in any encoding?

CPython versions tested on:

3.9, 3.11

Operating systems tested on:

Linux, Other

Linked PRs

Activity

  1. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Jul 10, 2025
  2. serhiy-storchaka commented on May 31, 2026

    @serhiy-storchaka
    Member

    I agree. The simplest way is to add errors='replace' or errors='surrogateescape'.

  3. added a commit that references this issue on Jun 10, 2026
  4. harjothkhara commented on Aug 3, 2026

    @harjothkhara
    Contributor

    PR gh-151216 is ready for review. It adds errors='replace' when reading the map files, as Serhiy suggested, with a test and NEWS entry. kulikjak tested it and confirmed it works. Can someone please take a look when you have time?

  5. added a commit that references this issue on Aug 4, 2026
  6. added 3 commits that reference this issue on Aug 4, 2026
  7. added a commit that references this issue on Aug 5, 2026
  8. added a commit that references this issue on Aug 14, 2026
  9. added a commit that references this issue on Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions