【问题标题】:Python open new files with same name of keys in dictionary in the json filePython在json文件中的字典中打开具有相同名称的新文件
【发布时间】:2020-08-30 13:48:25
【问题描述】:

我想创建与字典键名称相同的文件。例如我有一个这样的 json 文件

[{"Word": ["0"], "URL": "http://www..."},
 {"Word": ["10"], "URL": "http://www..."},
 {"Word": ["100"], "URL": "http://www..."},
 {"Word": ["1000"], "URL": "http://www..."},
 {"Word": ["11"], "URL": "http://www..."},]

我想打开一个键值名称为“0”、“10”、“100”、“1000”的文件,然后我想下载“URL”中字典值中的视频字典部分。

我正在尝试使用此代码访问 json 文件

import json

with open('filename.json') as f:

          data = json.load(f)
for words in data:
    
    x = words["Word"]

当我在那个循环中打印 x 时,我得到了这个 ["0"] 但我只想得到没有 " 或 [] 的 0,因为我将使用这个值通过这个方法创建文件

     os.mkdir('Videos')
     os.makedirs('Videos/0') 

for key_name in keys
    os.makedirs('Videos/"key_name "')

如何读取该 json 文件并使用 Json 文件中的键名打开新文件?

谢谢

【问题讨论】:

  • ["0"] 是一个常用的 Python 列表,您可以按通常的方式从中按索引检索第一项。

标签: python json


【解决方案1】:

您在位置0 处访问["Word"] 的键以获取列表中的第一项。

import os
import json

with open('file.txt') as f:
    data = json.load(f)

for words in data:
    x = words["Word"][0]
    new_dir = f'Videos/{x}'
    print(f'Create dir : {new_dir}')
    os.makedirs(new_dir)

输出:

Create dir : Videos/10
Create dir : Videos/100
Create dir : Videos/1000
Create dir : Videos/11

【讨论】:

    【解决方案2】:

    尝试获取列表的第一个元素

    x = words["Word"][0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2020-12-23
      • 2011-01-27
      相关资源
      最近更新 更多