Search code examples
pythondirectory-listing

How to get file path + file name into a list?


I am trying to get a list of strings with the file path and the file name. At the moment I only get the file names into the list.

Code:

hamFileNames = os.listdir("train_data\ham")

Output:

['0002.1999-12-13.farmer.ham.txt', 
 '0003.1999-12-14.farmer.ham.txt', 
 '0005.1999-12-14.farmer.ham.txt']

I would want an output similar to this:

['train_data\ham\0002.1999-12-13.farmer.ham.txt',
 'train_data\ham\0003.1999-12-14.farmer.ham.txt',
 'train_data\ham\0005.1999-12-14.farmer.ham.txt']

Solution

  • Since you have access to the directory path you could just do:

    dir = "train_data\ham"
    output = map(lambda p: os.path.join(dir, p), os.listdir(dir))
    

    or simpler

    output = [os.path.join(dir, p) for p in os.listdir(dir)]
    

    Where os.path.join will join your directory path with the filenames inside it.