formicaman
formicaman

Reputation: 1357

Get absolute path of files in sub-directory

I have a directory that consists of other directories. Each of those sub-directories have files that I need the absolute path for. For example, let's say the parent directory is /home/Documents and each of the sub-directories is 1, 2,..., 10. I have tried something like files = [os.path.abspath(f) for d in os.listdir('/home/Documents') for f in os.listdir(d)], but that gets me something like (for a file) /home/Documents/file1, when it should be /home/Documents/1/file1. Is there a way to do this with the sub-directory in there?

Upvotes: 0

Views: 1405

Answers (3)

yellowFlower
yellowFlower

Reputation: 37

Try this code below:

import os

def find_file_name(path=None):
    paths = []
    if not path:
        path = os.getcwd()
    for element in os.listdir(path):
        full_path = os.path.join(path, element)        
        if os.path.isdir(full_path):
            paths += find_file_name(path=full_path)
        else:
            paths.append(full_path)            
    else:        
        return paths
def find_file_name(path=None, extention=".pdf"):
    pdf_files = []
    if not path:
        path = os.getcwd()        
    for element in os.listdir(path):
        full_path = os.path.join(path, element)
        file = full_path.split("/")[-1]        
        if os.path.isdir(full_path):
            pdf_files += find_file_name(path=full_path)
        else:
            if extention in file:
                pdf_files.append(file)                              
    return pdf_files

Upvotes: 0

Harsha Reddy
Harsha Reddy

Reputation: 431

Yes. You can try os.walk. Consider the following path which has 3 sub directories: '1', '2', '3'.
- '1' has a file ("123.txt") - '2' is empty - '3' has 2 files ("123.txt", "1234.txt")

path = r"C:\Users\hvasala\Documents\Udemy Course\project\del"
import os
for dirname, _, filenames in os.walk(path):
    for filename in filenames:
        print(os.path.join(dirname, filename))

Output:
C:\Users\hvasala\Documents\Udemy Course\project\del\1\123.txt
C:\Users\hvasala\Documents\Udemy Course\project\del\3\123.txt
C:\Users\hvasala\Documents\Udemy Course\project\del\3\1234.txt

Upvotes: 2

Maurice Meyer
Maurice Meyer

Reputation: 18136

Use os.path.join:

root = '/tmp/project'
files = [os.path.join(root, d, f) for d in os.listdir(root) for f in os.listdir(os.path.join(root, d))]
print files

Output:

['/tmp/project/auth/__init__.py', '/tmp/project/controllers/__init__.py']

Upvotes: 1

Related Questions