简体   繁体   中英

Get full path for a file in python

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)

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM