Home > Mobile >  `os.path.join` doesn't return str?
`os.path.join` doesn't return str?

Time:08-25

in Python I wrote:

file_name = parse.unquote(os.path.basename(parse.urlparse(src).path))
directory = os.fsencode('./cache_folder')
file_path = os.path.join(directory, str.encode(file_name))
if imghdr.what(file_path).upper() not in ['J']:

But I'm getting the following warning:

Expected type 'str | PathLike[str] | _ReadableBinary', got 'bytes' instead

Why it got bytes? from what I know os.path.join returns PathLike[str]

and How might I fix this?

CodePudding user response:

EDITED:

encode() and os.fsencode() convert/encode string into bytes and this makes your problem.

Use

directory = './cache_folder'
file_path = os.path.join(directory, file_name)

OR you have to convert/decode bytes to string

directory = os.fsencode('./cache_folder')
file_path = os.path.join(directory, str.encode(file_name))

#file_path = str.decode(file_path)
file_path = file_path.decode()
  • Related