listdir-isdir-isfile usage explained

listdir-isdir-isfile usage explained

This three usage, must first obtain import os

the os.listdir (path) method, which returns a list that contains the names of directories and files in the path has a path

Note that this is only a return to the names of files and subdirectories in a path, not included. Files and ...

Whether os.path.isdir (filename) and os.path.isfile (filename) file isfile to determine filename or subdirectory isdir

Note that: filename is the absolute path of the file, including the full name

Common mistakes: direct use os.listdir (path) return value as os.path.isdir (filename) and os.path.isfile (filename) The filename value can not determine the cause, which is often confused place

Correct usage: filename need python path stitching os.path.join (path, file) function, which is the path if the current directory, you can get by os.getcwd (), file is the file name without the path, the following are available The method of obtaining traversing (the actual application, remove #)

#递归遍历目录样例文件
#导入oS模块
import os
#待遍历的目录路径
path= "e:\办公"
#调用walk方法递归遍历path目录
for root, dirs, files in os.walk(path):
	for name in files: 	#如只要文件名,只保留这个FOR
		print(os . path. join(root, name))
	for name in dirs:	#如只要目录,只保留这个FOR
		print(os.path. join(root, name))

The filename is determined after a good splicing tape path, and then for os.path.isdir () The os.path.isfile and (). The

I wish you all detours.

Released two original articles · won praise 0 · Views 66

Guess you like

Origin blog.csdn.net/weixin_45903952/article/details/103999285