简体   繁体   中英

python equivalent of perl's “opendir”

What I am essentially looking for is a way to return a handle to a directory in python, a bit like how perl can do something like this...

opendir CWD .

see: http://perldoc.perl.org/5.8.9/functions/opendir.html

CWD can then be used as a handle for pointing to the directory like *CWD in file operations.

The closest I've come across in python is open() but that doesn't return file descriptors/pointers and doesn't work with directories.

The scandir function opens a handle and allows you to walk through each file iteratively. This is useful for the one of the same reasons as opendir : it's far more efficient when there could be a large number of files:

https://docs.python.org/3/library/os.html#os.scandir

The other use of opendir is the ability to retain a reference to the inode, rather than the path.

The generator returned by scandir can be passed around, like CWD, and it will retain the "inode-like" functionality of CWD. For example, you can obtain a generator for scandir and then rename the underlying folder, and the generator remains valid.

However it cannot be "reset back" to the beginning. AFAICT this is the only thing perl can do that python cannot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM