0

Newbie in python, I have the following code:

XX = [A,B,C,D,E]
src_path = 'C:\love\hi_XX\you'

for file in src_path:
    Do something....

I want to loop through all files in C:\love\hi_A\you first, then C:\love\hi_B\you all the way to C:\love\hi_E\you.

I am using Spyder. How do I make this work? Thank you.

3
  • what are you looking for? to read or write to file? Commented Oct 11, 2016 at 18:30
  • Looking for a way help to use for loop through all folders without repeat the 5 times for loop Commented Oct 11, 2016 at 18:43
  • Awesome. Thank you AJNeufeld Commented Oct 11, 2016 at 18:56

3 Answers 3

2

You can create the src_path that you want by using a for loop against the elements in XX

for X in XX:
    src_path = r'C:\love\hi_' +X + r'\you'

Then, within that loop, you can use os.walk like in the other answer

import os
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))
Sign up to request clarification or add additional context in comments.

3 Comments

Got error said A, B C... undefind name. Then I pgot error can't assign to literalut A= 'A', B = 'B'
are you trying to say you can't enter the command A='A' ?
Got the solution from AJNewfeld
1

There's a function for that in the standard "os" module.

https://docs.python.org/2/library/os.html#os.walk

1 Comment

Read through, but not applied in my case. Thanks
0

You need quotes around your literals in your array. And os.path.join is a always a good idea for joining together path components:

import os.path
XX = ["A", "B", "C", "D", "E"]
for X in XX:
    src_path = os.path.join(r'C:\love', "hi_"+X, "you")
    print(src_path)

C:\love\hi_A\you
C:\love\hi_B\you
C:\love\hi_C\you
C:\love\hi_D\you
C:\love\hi_E\you

Finally, if C:\love\hi_XX\you are directories, and you need files beneath them, then use os.walk on your src_path values.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.