Get full path for a file in python
Question: I'm trying to create a csv of paths to wav files in a series of directories.
Each row should correspond to a directory. Each cell in a row should contain
the path to a single file. The script below is "almost" working. It creates a
CSV with the files as cells. However, os.path.realpath and os.path.abspath
don't include the direct parent directory of the file. So, instead of
"/root/directory/file.wav". I'm getting "/root/file.wav".

    
    
    import fnmatch
    import os
    import csv
    
    with open('filelist.csv', 'wb') as csvfile:
        lister = csv.writer(csvfile, delimiter=',')
        for root, dirnames, filenames in os.walk(os.getcwd()):
          matches = []
          for filename in fnmatch.filter(filenames, '*.wav'):
            matches.append(os.path.realpath(filename))
            if len(matches) > 0:
              print matches
              lister.writerow(matches)
    


Answer: You need to `join` the `root` path to get a relative path from the current
directory, _then_ you can call `abspath`.*

You can see this in every one of the examples for
[`os.walk`](https://docs.python.org/2/library/os.html#os.walk) in the docs,
like this one:

    
    
    import os
    for root, dirs, files in os.walk(top, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    

* * *

So, for your code:

    
    
    with open('filelist.csv', 'wb') as csvfile:
        lister = csv.writer(csvfile, delimiter=',')
        for root, dirnames, filenames in os.walk(os.getcwd()):
            matches = []
            for filename in fnmatch.filter(filenames, '*.wav'):
                matches.append(os.path.abspath(os.path.join(root, filename)))
                if len(matches) > 0:
                    print matches
                    lister.writerow(matches)
    

* * *

* Alternatively, you can start the `walk` with an absolute path and not have to `abspath` each file… but only if you understand what that means for symlinks and are happy with that. If you don't know, use `abspath` on each file.

