Home > Back-end >  Is there a way to look one level down from the current directory without explicitly calling for it
Is there a way to look one level down from the current directory without explicitly calling for it

Time:02-15

Here is the code I have. Is there a way to look into all the files/folders in folderName? I'm assuming I'll use a nested for loop to iterate through each file/folder in folderName.

import os
import sys
import pandas as pd
import xlrd
import shutil
import numpy

#set the destination folder to variable
destination = 'G:\\path\\to\\destination\\'

matrix = []
matrix.append([])
matrix.append([])

#client folder name in index 0 of matrix, client performance folder in index 1 of matrix
for folderName in os.listdir(destination):
    matrix[0].append(folderName) #client folder name

CodePudding user response:

if i got you right you need to go recursively through all the subfolders ...

For this purpose you should use the os.walk function like this :

for root, dirs, files in os.walk(): 
    #do something  like  matrix[0].append(folderName) #client folder name  

root will be taken as "current", as long as it is exausted and then will be changed with the next one from the dirs-list

Good luck :)

Remark:

os.listdir takes the content only of the current folder and doesn't go deeper in the structure of subfolders

CodePudding user response:

Documentation and examples for os.walk provided here so really no need to repeat.

  • Related