Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through files

Tags:

python

pathlib

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

like image 455
FooBar Avatar asked May 21 '14 11:05

FooBar


People also ask

How do I iterate through a file in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).


2 Answers

I guess you should use Path.iterdir().

for pth in dir_.iterdir():

    #Do your stuff here
like image 54
Alex Shkop Avatar answered Sep 20 '22 00:09

Alex Shkop


Try

for pth in dir_.iterdir():

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

like image 27
Lee Thomas Avatar answered Sep 19 '22 00:09

Lee Thomas