Iterate through files

16,184

Solution 1

I guess you should use Path.iterdir().

for pth in dir_.iterdir():

    #Do your stuff here

Solution 2

Try

for pth in dir_.iterdir():

Related documentation here: https://docs.python.org/3/library/pathlib.html#pathlib.Path.iterdir

Solution 3

Use glob module instead, which works same on both platforms:

import glob
for item in glob.glob('/your/path/*')  # use any mask suitable for you
   print item # prints full file path

Solution 4

dir_ = pathlib.Path(str(somePathVariable))
os.chdir(str(dir_))
for pth in dir_:        
    # some operations here

Now your code will work on both platforms. You are specifing de type of path... if you want it to be cross-platform you have to use "Path" not "PosixPath"

Share:
16,184
FooBar
Author by

FooBar

Updated on July 01, 2022

Comments

  • FooBar
    FooBar almost 2 years

    I'm trying to adapt someone's code for my (Windows 7) purposes. His is unfortunately UNIX specific. He does

    dir_ = pathlib.PosixPath(str(somePathVariable))
    os.chdir(str(dir_))
    for pth in dir_:        
        # some operations here
    

    Running this, I got (not surprisingly)

    NotImplementedError: cannot instantiate 'PosixPath' on your system
    

    I looked into the documentation for pathlib and thought yeah, I should just be able to change PosixPath to Path and I would be fine. Well, then dir_ generates a WindowsPath object. So far, so good. However, I get

    TypeError: 'WindowsPath' object is not iterable
    

    pathlib is at version 1.0, what am I missing? The purpose is to iterate through files in the specific directory. Googling this second error gave 0 hits.

    Remark: Could not use pathlib as a tag, hence I put it into the title.

    Update

    I have Python 2.7.3 and pathlib 1.0

  • Jim Oldfield
    Jim Oldfield almost 8 years
    You can use the .glob() method on Path objects; no need to switch back to the legacy functions.
  • PaulMcG
    PaulMcG about 7 years
    In the past, I found the glob.glob() on Windows returns a list of filenames in lexical order, while on Linux order is not guaranteed. So when I ported code from Win to Linux, I had to sort the results from glob.glob() to have consistent behavior. I don't know if Path.glob is similar, but it is worth checking.
  • Paul Rougieux
    Paul Rougieux over 2 years
    for path in Path(".").glob("*.csv"): print(path) keeps only specific file extensions.