python - 如何使用循环读取许多不同名称的文件?我如何写入 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":[""]
} ] }
提前致谢
解决方案
尝试这个:
- 创建文件名列表。这需要您手动输入文件名。
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
- 创建一个变量来存储文件内容。此变量将存储每次迭代的文件文本。“File_in”是一个空列表,可以存储每次迭代时每个文件的内容。
file_in = list()
- 使用“for”循环循环遍历文件名列表中的每个文件名。这将确保每个文件都打开并在“file_in”列表中有一个引用变量:
x = 0 for item in filenames:
file_in[x] = open(item, 'r')
x += 1
推荐阅读
- crosstab - Cognos Crosstab Rows - 来自数据的标签值
- reactjs - React 设计问题:具有相同 UI 布局但数据不同的多个页面
- c# - 调试 .net core Application System.StackOverflowException c#
- php - 网站下载 php 文件而不是加载页面 NGINX
- sql - 执行查询中创建的多个 SQL 字符串
- php - PHP页面上的分页部分更新
- python - 如果密码以数字开头,是否有更简单的方法可以再次生成密码?
- python - VS Code - 如何使数据框以 Excel 格式显示?
- css - React Native:由文本高度定义大小的 FlatList Header 有时不会完全显示
- iptables - 双网卡之间的本地 mitmproxy (iptables)