import osdef file_search(str_search): dir = os.getcwd()#得到當前目錄 for root, dirs, files in os.walk(dir):#遍歷根目錄 for file in files: if str_search in file: path = os.path.join(root,file)#合并路徑 relpath = os.path.relpath(path,dir)#相對路 徑,去掉當前位置 PRint(relpath)if __name__ == '__main__': str_search = input('輸入字符串,將打印出包含該字符串的文件的相對路徑:') file_search(str_search)
在os.walk中root保存路徑, for file in files,只檢索文件名字,不檢索dirs(文件夾)