Iterate through files

I am trying to adapt the code for my (Windows 7) goals. Its unfortunately unix. He does

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

By launching this, I got (not surprising)

NotImplementedError: cannot instantiate 'PosixPath' on your system

I looked through the documentation for pathliband thought that I should just change PosixPathto Path, and everything will be fine. Well then dir_generates an object WindowsPath. So far, so good. However i get

TypeError: 'WindowsPath' object is not iterable

pathlibis in version 1.0, what am I missing? The goal is to iterate over files in a specific directory. As a result of this second error, 0 hits were received.

Note. Cannot be used pathlibas a tag, so I put it in the header.

Update

I have Python 2.7.3 and pathlib 1.0

+4
source share
4

, Path.iterdir().

for pth in dir_.iterdir():

    #Do your stuff here
+6

glob, :

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

for pth in dir_.iterdir():

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

+1
source
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 specify the type of path ... if you want it to be cross-platform, you need to use "Path" and not "PosixPath"

+1
source

Source: https://habr.com/ru/post/1541416/


All Articles