将下载的文件位置写入json文件

时间:2019-03-05 14:33:26

标签: python python-3.x youtube-dl

我写了这个脚本:

with open('data.json', 'r') as f:
    data = json.load(f)


for obj in data:
    video_player_url = obj.get('video_url')
    ydl_opts = {}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([video_player_url])
    print(video_player_url)
    location = 'C:/Users/name/video/'obj.get('text')'.mp4'
    info = {"text": obj.get('text'), "video_location": 'location', "tags": obj.get('tags')}
    downloaded_file = open('downloaded_files','w+')
    json.dump(info, downloaded_file)

下载很好,但是我想将下载的文件位置写在json文件上。 我在这里给我带来的错误。

写json文件,我得到的是:

{"text": "Title", "video_location": "C:/Users/name/video/video.mp4", "tags": ["", "tag", "", "tag2", "tag3"], "description": "great video"}{"text": "Title2", "video_location": "C:/Users/name/video/video2.mp4", "tags": ["", "tag", "", "tag2", "tag3"], "description": "great video2"}{"text": "Title3", "video_location": "C:/Users/name/video/video3.mp4", "tags": ["", "tag", "", "tag2", "tag3"], "description": "great video3"}

但是我想要的是:

[
{"text": "Title", "video_location": "C:/Users/name/video/video.mp4", "tags": ["", "tag", "", "tag2", "tag3"], "description": "great video"}
{"text": "Title2", "video_location": "C:/Users/name/video/video2.mp4", "tags": ["", "tag", "", "tag2", "tag3"], "description": "great video2"}
{"text": "Title3", "video_location": "C:/Users/name/video/video3.mp4", "tags": ["", "tag", "", "tag2", "tag3"], "description": "great video3"}
]

1 个答案:

答案 0 :(得分:0)

它一直被覆盖,因为您没有将当前字典存储在任何地方,而只是覆盖了info中存储的旧字典。尝试使用list存储info dictionary

with open('data.json', 'r') as f:
data = json.load(f)

final_json_list = list()
for obj in data:
    video_player_url = obj.get('video_url')
    ydl_opts = {}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
         ydl.download([video_player_url])
    print(video_player_url)
    location = 'C:/Users/name/video/'obj.get('text')'.mp4'
    info = {"text": obj.get('text'), "video_location": 'location', "tags": obj.get('tags')}
    final_json_list.append(info)

downloaded_file = open('downloaded_files','w+')
json.dump(final_json_list, downloaded_file)   
相关问题