折腾:
【未解决】用Python代码从视频中提取出音频mp3文件
期间,需要去对于:
此处的user目录,进行子文件夹的遍历,获取所有子目录
python 目录 子文件夹
python list sub folder file
Python : How to get list of files in directory and sub directories – thispointer.com
所以感觉有两种方式
os.listdir和os.walk
看看哪个更合适
python os.listdir vs os.walk
好像还有个scandir
“scandir has been included in the Python 3.5 standard library as os.scandir(), ”
所以此处Python 3.5+,直接用:
“from os import scandir, walk”
就好了。
发现还有个glob:
感觉是:
此处Python 3.6,直接去用
“os.listdir(path=’.’)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries ‘.’ and ‘..’ even if they are present in the directory.
path may be a path-like object. If path is of type bytes (directly or indirectly through the PathLike interface), the filenames returned will also be of type bytes; in all other circumstances, they will be of type str.
This function can also support specifying a file descriptor; the file descriptor must refer to a directory.
Note
To encode str filenames to bytes, use fsencode().
See also
The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases.
Changed in version 3.2: The path parameter became optional.
New in version 3.3: Added support for specifying an open file descriptor for path.
Changed in version 3.6: Accepts a path-like object.”
“os.scandir(path=’.’)
Return an iterator of os.DirEntry objects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries ‘.’ and ‘..’ are not included.
Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. “
scandir比listdir性能好很多
然后用代码:
import os import logging OutputFolder = "/Users/crifan/dev/tmp/xxx_downloadDemo/output" def processVideo(): userFolder = os.path.join(OutputFolder, "user") logging.info("userFolder=%s", userFolder) with os.scandir(userFolder) as dirEntryList: for curDirEntry in dirEntryList: logging.info("curDirEntry=%s", curDirEntry) # <DirEntry '432824'> if curDirEntry.is_dir(): dirName = curDirEntry.name logging.info("dirName=%s", dirName) # 432824 else: logging.warn("Omit non-dir: %s", curDirEntry.name)
就可以获取文件夹的列表,以及判断每个是否是目录还是文件了:
转载请注明:在路上 » 【已解决】Python中获取某文件夹的子目录的列表