0

I wanted to generate URLs for all files in a folder hierarchy

for path, folder, files in os.walk("C:/Users/guptamols/Course/tutorials"):
     for names in files:
     print(os.path.join(path,names))

Result:

C:/Users/guptamols/Course/tutorials\ch1\Ass1.txt
C:/Users/guptamols/Course/tutorials\ch1\Ass2.txt

I found that these issues can be resolved using the Pathlib module, So i tried:

from pathlib import Path
for path, folder, files in os.walk("C:/Users/guptamols/Course/tutorials"):
    for name in files:
        Path.joinpath(path,names)

It gives this error

AttributeError: 'str' object has no attribute '_make_child'

Where am i going wrong?

Gupta
  • 314
  • 4
  • 17

1 Answers1

0

To use Path.joinpath, you should construct a Path object from path first:

import os
from pathlib import Path

for path, folder, files in os.walk("C:/Users/guptamols/AppliedAI New/tutorials"):
    for name in files:
        p = Path(path)       # p is a Path object
        p = p.joinpath(name) # now we appended name to it
        print(p)

When invoked as a method of a Path instance, the first argument is that instance: p.joinpath(name) above can be alternatively written Path.joinpath(p, name).

Alternatively, you can use os.path.join, so that you don't need to construct any Path objects at all:

import os

for path, folder, files in os.walk("C:/Users/guptamols/AppliedAI New/tutorials"):
    for name in files:
        print(os.path.join(path, name))

If you then want to convert path separators to the native form, like pathlib does by default, you can use os.path.normpath.

user3840170
  • 26,597
  • 4
  • 30
  • 62