取得 home 目录
例如我在我的本机上面
Input
os.path.expanduser("~")
Output
'/Users/edwin'
os.path.basename() 和 os.path.dirname() 的区别
- os.path.basename() 取得路径的尾部
- os.path.dirname() 取得路径的前部
Input
path = '/Users/edwin/develop/foo'
os.path.basename(path)
os.path.dirname(path)
Output
foo
/Users/edwin/develop/
os.walk()
os.walk(path) 可以遍历以path作为根节点的文件系统。对于需要取得文件目录信息的应用是非常有用的。这里会用一个实例来解释:
- 目的,取得除img文件夹之外所有的文件
- 代码
# 建一个空List
fname = []
# 我们把**img**加到需要忽略的文件夹组中
ignore_list = ['img']
# 循环处理os.walk('~/docs')的结果
for dirpath,dirnames,filenames in os.walk('~/docs'):
if os.path.basename(dirpath) in ignore_list:
# 清空dirnames 和 filenames, 如果取得文件夹的当前根目录在ignore_list 中
dirnames[:] = []
filenames[:] = []
# 取filenames中的值
for f in filenames:
fname.append(os.path.join(dirpath, f))
- 输出
~/docs/api_m.md
~/docs/index.md
~/docs/kafka_cli.md
~/docs/kafka.md
~/docs/Legacy.md
~/docs/poslog.md
- 解释:
os.walk(path) 会返回3个值,分别是dirpath: 正在遍历的文件目录的路径, dirnames:该文件目录下所有的文件夹, filenames:该文件目录下(此文件目录层)所有的文件.
官方文档的解释:
dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).