Python 中当前位置以及目录文件遍历操作

Python 中当前位置以及目录文件遍历操作

当前位置

  • print(os.path.dirname(__file__))
    • 其中 dirname 会选择目录(文件夹),"__file__" 内置变量,标识当前编写文件位置
  • print(os.getcwd())

目录遍历

import glob

for filename in glob.glob(rootdir+'*/*.md'):
    print(filename,end='
 new_way')
import os

rootdir=os.path.dirname(__file__)+'./TranslateProject/sources/'
for parent,dirnames,filenames in os.walk(rootdir):    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
    for filename in filenames:                        #输出文件信息
        print(os.path.join(parent,filename))          #输出文件路径信息

原文地址:https://www.cnblogs.com/itxdm/p/6798393.html