首页 > 解决方案 > 如何使用循环读取许多不同名称的文件?我如何写入 json 文件?

问题描述

示例:静态目录中的 S1-1.jpg、S1-2.jpg、S1-3.jpg

现在我是这样写的,但看起来很乱

image = open('./static/S1-1.jpg', 'rb') #open binary file in read mode
            image_read = image.read()
            image_64_encode = base64.encodestring(image_read)
image.close()

image = open('./static/S1-2.jpg', 'rb') #open binary file in read mode
            image_read = image.read()
            image_64_encode = base64.encodestring(image_read)
image.close()

image = open('./static/S1-3.jpg', 'rb') #open binary file in read mode
            image_read = image.read()
            image_64_encode = base64.encodestring(image_read)
image.close()

我想写入 json 文件的“URL”

json 文件的示例

{ "intents": [ {
    "tag": "S1-1",
    "patterns": ["Where is S1-1", "S1-1", "Find S1-1","How to go to S1-1","Where S1-1"],
    "responses": ["S1-1 : Blue is Library, Red is destination."],
    "URL":[""]
    } ] }

提前致谢

标签: python

解决方案


尝试这个:

  1. 创建文件名列表。这需要您手动输入文件名。
    filenames = ['file1.txt', 'file2.txt', 'file3.txt']
  1. 创建一个变量来存储文件内容。此变量将存储每次迭代的文件文本。“File_in”是一个空列表,可以存储每次迭代时每个文件的内容。
    file_in = list()
  1. 使用“for”循环循环遍历文件名列表中的每个文件名。这将确保每个文件都打开并在“file_in”列表中有一个引用变量:
    x = 0 for item in filenames:
        file_in[x] = open(item, 'r')  
        x += 1

推荐阅读