Python Forum

Full Version: os.walk(Path("path_string")) giving error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is this correct

dir = "E:\\Books"
p = Path(dir)
reference : https://pbpython.com/pages/mailinglist.html

os.walk(p)
giving below error:

File "F:\Users\hyg\AppData\Local\Programs\Python\Python35\lib\os.py", line 368, in walk
scandir_it = scandir(top)
TypeError: scandir: illegal type for path parameter

However
os.walk(dir)
works fine
p looks like a pathlib Path, not an os path.
Hard to be sure without full code.
dir = "E:\\Books"
p = Path(dir)
if that is the case, then you can still use os, but you must resolve p first:
os.walk(p.resolve())
better to use a pathlib walk instead (Google: 'pathlib equivalent of os.walk')
Yes, i have imported pathlib
complete code:

from pathlib import Path 
import os

dir_to_scan = "E:\\Books"
p = Path(dir_to_scan)
q = p / 'jpg'
print(q)

for dirName, subdirList, fileList in os.walk(p):
    print('Found directory: %s' % dirName)
    for fname in fileList: 
        print('\t%s' % fname)
It does not say what you are importing, but these should both work:

from pathlib import Path
import os

dir = "D:\\Temp2"
path = Path(dir)

for item in os.walk(path):
    print('path',item)

for item in os.walk(dir):
    print('dir',item)
Paul
(May-10-2020, 06:24 AM)Kumarkv Wrote: [ -> ]TypeError: scandir: illegal type for path parameter
You get this error because you use Python 3.5.
Have to use Python 3.6 or newer for os.walk() to take pathlib object.
You use can it directly like this os.walk(dir_to_scan).
You should of course install a new version Python 3.8 (3.6-3.7) and pip installation under Windows

Then you can also drop the old string formatting %s' % dirName and use f-string.
from pathlib import Path
import os

dir_to_scan = r"C:\code\img"
p = Path(dir_to_scan)
for root, dirs, files in os.walk(p):
    for fname in files:
        if fname.endswith(('.jpg', '.png')):
            print(f'Image found --> {fname}')
Output:
Image found --> nrk.png Image found --> test.jpg