1
votes

I have written the following code to get path for files in sub_folder.

import os
os.chdir('C:\Users\mike\Desktop\a')
base_dir = os.getcwd()
sub_dirs = [os.path.join(base_dir, d) for d in os.listdir(base_dir)]
for i in os.listdir(sub_dirs):
    path = [os.path.join(sub_dirs), i]

but it does not work and I get this error: Traceback (most recent call last): File "C:\Users\mike\Desktop\mine1.py", line 6, in for m in os.listdir(sub_dirs): TypeError: coercing to Unicode: need string or buffer, list found

what is the problem?

Cheers

3
What do you want os.path.join(sub_dirs) to do? - Anand S Kumar
I want to have a path for my text file like this : >>> path 'C:\\Users\\mike\\Desktop\\a\x03\x01.txt' - Mike
Off-topic: Use raw strings for string literal Windows paths, or you're going to get a nasty surprise the first time a path component begins with, for example, a, b, f or n (possibly a few others). With a non-raw string, \b is the ASCII backspace character, not a backslash followed by b, and similar issues apply to the other examples. It's best to be safe and always use raw strings, e.g., in your example, r'C:\Users\mike\Desktop\a' (note leading r before open quote). - ShadowRanger

3 Answers

0
votes

os.listdir needs an string or unicode as an argument. Your sub_dirs is a list of string.

0
votes

Does the following solve your problem?

import os
os.chdir('C:\Users\mike\Desktop\a')
rootDir = os.getcwd()
fileSet = set()

for dir_, _, files in os.walk(rootDir):
    for fileName in files:
        relDir = os.path.relpath(dir_, rootDir)
        relFile = os.path.join(relDir, fileName)
        fileSet.add(relFile)
0
votes

Hooray for recursion!

def recurse(files, directory):
    for item in os.listdir(directory):
        full_path = os.path.join(directory, item)
        if os.path.isdir(full_path):
            recurse(files, full_path)
        else:
            files.append(full_path)

files = []
recurse(files, 'C:\Users\mike\Desktop\a')

Now your "files" list will be filled.

If you want to be able to loop over each directory's contents, you can put them in sub lists:

def recurse(directories, directory):
    files = []
    for item in os.listdir(directory):
        full_path = os.path.join(directory, item)
        if os.path.isdir(full_path):
            recurse(directories, full_path)
        else:
            files.append(full_path)
    if len(files) > 0:
        directories.append((directory, files))

directories = []

recurse(directories, 'C:\Users\mike\Desktop\a')

for directory, files in directories:
    # "directory" is provided as reference (eg "C:\Users\mike\Desktop\a\a1")
    for path in files:
        # loop over each file in "directory"
        pass