0

Is it possible to append to different lists while looping through multiple directories simultaneously? my code:

def trav(dir_1, dir_2):
    data_0= []
    data_1 = []
    for dir in [dir_1, dir_2]:
        for path, dirs, files in os.walk(dir):
             for file in files:
                 for line in file:
                      data_0.append(line)

How do I append line from dir_1 -> data_0 and appand dir_2 -> data_1 using one loop, I know i can write two separate methods but would like to know if there is a more efficient, simpler way of doing it. I tried using chain from itertools, but no luck with that, any suggestiosn?

1
  • tried itertools.chain(), but couldn't quite understand how to append file contents to a specific list @AhsanulHaque
    – octain
    Oct 25, 2015 at 18:23

2 Answers 2

2

If you do not want two loops its okay you can simply perform an if

def trav(dir_1, dir_2):
    data_0 = []
    data_1 = []
    for dir in [dir_1, dir_2]:
        current_dir = dir
        for path, dirs, files in os.walk(dir):
             for file in files:
                 for line in file:
                      if current_dir == dir_1:
                          data_0.append(line)
                      else:
                          data_1.append(line)

another way could be:

def trav(dir_1, dir_2):
    data_0 = []
    data_1 = []
    for dir in [dir_1, dir_2]:
        if dir == dir_1:
            data = data_0
        else:
            data = data_1
        for path, dirs, files in os.walk(dir):
             for file in files:
                 for line in file:
                     data.append(line)

Second one will run faster than the first one, since number of comparison needed will be lesser.

2

Well, you could make data a dict:

def trav(dir_1, dir_2):
    data = {}
    data[dir_1] = []
    data[dir_2] = []
    for dir in [dir_1, dir_2]:
        for path, dirs, files in os.walk(dir):
             for file in files:
                 for line in file:
                      data[dir].append(line)

Or you could make data a collections.defaultdict(list). Then you wouldn't have to initialize the entries to empty lists. Also, I would suggest you not use the name dir because of confusion with the built-in name. There's no harm done here though, because it's a local variable.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.