Iterate through files
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"
FooBar
Updated on July 01, 2022Comments
-
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 changePosixPath
toPath
and I would be fine. Well, thendir_
generates aWindowsPath
object. So far, so good. However, I getTypeError: '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 almost 8 yearsYou can use the
.glob()
method on Path objects; no need to switch back to the legacy functions. -
PaulMcG about 7 yearsIn 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 fromglob.glob()
to have consistent behavior. I don't know ifPath.glob
is similar, but it is worth checking. -
Paul Rougieux over 2 years
for path in Path(".").glob("*.csv"): print(path)
keeps only specific file extensions.