Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - TypeError: Can't mix strings and bytes in path components

Tags:

python

The following code:

import os

directory_in_str = 'C:\\Work\\Test\\'
directory = os.fsencode(directory_in_str)

for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.lower().endswith(".xml"):
        with open(os.path.join(directory, filename), 'r') as handle:
            for line in handle:
                print(line)
    else:
        continue

is giving me this error:

Traceback (most recent call last):
  File "c:\Work\balance_search2.py", line 9, in <module>
    with open(os.path.join(directory, filename), 'r') as handle:
  File "C:\ProgramData\Anaconda3\lib\ntpath.py", line 114, in join
    genericpath._check_arg_types('join', path, *paths)
  File "C:\ProgramData\Anaconda3\lib\genericpath.py", line 151, in _check_arg_types
    raise TypeError("Can't mix strings and bytes in path components") from None
TypeError: Can't mix strings and bytes in path components

Can anyone help me fix it please.

like image 382
Superdooperhero Avatar asked Feb 11 '18 07:02

Superdooperhero


1 Answers

Just remove this line: directory = os.fsencode(directory_in_str). There is no need to encode the directory name.

like image 78
DYZ Avatar answered Nov 16 '22 01:11

DYZ