Reputation: 391
I probably will have 3 questions on this file but for now I will focus on the problem, not the addition i need to make. I have a script that is working perfectly to create a json file of directory contents. The problem I have is on line 9. The output it is giving me is correct, however the directory path is not loading correctly in the audio player application because the directory paths needs prepended with ../audio/
Here is the script:
import os
import errno
def path_hierarchy(path):
hierarchy = {
# 'name': os.path.basename(path),
'artist': os.path.basename(path),
'album': 'Node 42177',
'url': os.path.basename(path), # HERE!
'cover_art_url': '../album-art/Radio.jpg',
}
try:
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
]
except OSError as e:
if e.errno != errno.ENOTDIR:
raise
#hierarchy['type'] = 'file'
return hierarchy
if __name__ == '__main__':
import json
import sys
try:
directory = sys.argv[1]
except IndexError:
directory = "."
print(json.dumps(path_hierarchy(directory), indent=2, sort_keys=True))
I have tried everything I can think of to insert the ../audio/ at the beginning of the url string but keep getting errors. Could anyone tell me the syntax needed please?
Upvotes: 0
Views: 440
Reputation: 64
In line 9, in order to prepend, you have to call the os.path inside os.joi as in the following example:
'url': os.path.join("..","audio",os.path.basename(path))
It will give you:
"url": "..\\audio\\path"
Another suggestion is to change this part:
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
]
for this:
hierarchy['children'] = [
path_hierarchy(os.path.join(path, contents))
for contents in os.listdir(path)
if os.path.isdir(os.path.join(path, contents))
]
If you intend to take only directories, this 'if' will allow the loop ignore files.
Upvotes: 3
Reputation: 82785
Try using os.path.join
Ex:
hierarchy = {
# 'name': os.path.basename(path),
'artist': os.path.basename(path),
'album': 'Node 42177',
'url': os.path.join("../audio/", os.path.basename(path)),
'cover_art_url': '../album-art/Radio.jpg',
}
Upvotes: 2