Navigation problems navigation with os.walk

I am relatively new to python and I try my best over the weekend. I want to navigate my music directories and get the artist name of each music file and export it to csv so that I can update my music collection (a lot from when I was younger and didn't care about quality).

Anyway, I am trying to get the path to each music file in its respective directory, so I can pass it to the id3 tag reader to get the artist name.

Here's what I'm trying:

import os

def main():
    for subdir, dirs, files in os.walk(dir):
        for file in files:
            if file.endswith(".mp3") or file.endswith(".m4a"):
                print(os.path.abspath(file))

      

However .abspath () doesn't do what I think it should. If I have a directory like this:

music
--1.mp3
--2.mp3
--folder
----a.mp3
----b.mp3
----c.mp3
----d.m4a
----e.m4a

      

and I run my code, I get this output:

C:\Users\User\Documents\python_music\1.mp3
C:\Users\User\Documents\python_music\2.mp3
C:\Users\User\Documents\python_music\a.mp3
C:\Users\User\Documents\python_music\b.mp3
C:\Users\User\Documents\python_music\c.mp3
C:\Users\User\Documents\python_music\d.m4a
C:\Users\User\Documents\python_music\e.m4a

      

I am confused why it doesn't show 5 files inside the folder. Other than that, am I even going to do this in the easiest or best way? Again, I am new to python, so any help is appreciated.

+3


source to share


1 answer


You are only passing the filename in os.path.abspath()

, which has no context other than your current working directory.

Join path with parameter subdir

:

print(os.path.join(subdir, file))

      

From the os.path.abspath()

documentation
:

On most platforms, this is equivalent to a function call normpath()

as follows: normpath(join(os.getcwd(), path))

.



so if your current working directory C:\Users\User\Documents\python_music

all your files are linked to it.

But os.walk

it gives you the correct location for the base filenames; from the documentation :

For each directory in the tree rooted at the top of the directory (including the top), it gives a 3-tuple (dirpath, dirnames, filenames)

.

dirpath is string, directory path. [...] filenames is a list of filenames without a directory in the dirpath directory. Note that the names in the lists do not contain path components. To get the full path (which starts with top) to a file or directory in dirpath, do os.path.join(dirpath, name)

.

Emphasis on mine.

+4


source







All Articles