python - 根据接收到的字典信息动态写入文本文件
问题描述
我正在尝试根据字典信息将作业写入文本文件。字典信息是从服务器接收的,并不总是相同的。它包含file_count
并且file_paths
是file_paths
一个列表。例如,
{'file_paths': ['/file/path/one', '/file/path/two'], 'file_count': 2}
我有一个基线来写出一段文本,其中包含将根据字典信息插入的变量。例如,
text_baseline = ('This is the %s file\n'
'and the file path is\n'
'path: %s\n')
需要根据从字典中接收并写入文本文件的文件数量复制此基线。
因此,例如,如果字典有三个文件,它将有三个文本块,每个文本块都包含文件号和路径的更新信息。
我知道我必须做这样的事情:
f = open("myfile.txt", "w")
for i in dict.get("file_count"):
f.write(text_baseline) # this needs to write in the paths and the file numbers
我很难弄清楚如何根据使用基线收到的信息更新路径和文件编号。
解决方案
使用 str.format() 格式化字符串。
data = {'file_paths': ['/file/path/one', '/file/path/two'], 'file_count': 2}
text_baseline = "this is the {}th file and the path is {}"
with open('path','w') as f:
for i in range(int(dict.get('file_count'))):
f.write(text_baseline.format(i,data['file_paths']))
推荐阅读
- c - 查找二维数组中唯一行和列的索引以及这些位置中元素的最小总和
- firebase - Flutter 将 Firestore UID 传递到存储库
- php - PHP 数组 - 范围键
- lotus-notes - 无法在 Notes 中调用数据库脚本文档。找不到外部名称错误
- flutter - Flutter 令人费解的流行为:调用 setState 但不重建 widget 树
- javascript - googlesheet 按列名复制和粘贴过滤后的数据
- c++ - C++ 返回一个承诺/未来
- python - 创建列表而不是数组
- powershell - 通过 PowerShell 获取已卸载 Windows 字体的详细信息
- c++ - 如何逐行搜索某些字符串的关键字