【问题标题】:Dynamically writing to text file based on received dictionary information根据接收到的字典信息动态写入文本文件
【发布时间】:2018-10-04 00:50:07
【问题描述】:

我正在尝试根据字典信息将作业写入文本文件。字典信息是从服务器接收的,并不总是相同的。它包含file_countfile_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

我很难根据使用基线收到的信息来确定如何更新路径和文件编号。

【问题讨论】:

  • 对于所示的输入,您希望看到什么输出?

标签: python python-3.x dictionary file-writing


【解决方案1】:

使用 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']))

【讨论】:

  • 我用的是python3.4那个版本支持字符串格式吗?
  • 支持
  • 你缺少一些紧密的括号
  • @MadPhysicist 我确实错过了最后的那些。谢谢。
  • 仍然不足
【解决方案2】:

这里可以使用枚举和字符串格式:

paths = {'file_paths': ['/file/path/one', '/file/path/two'], 'file_count': 2}
text_baseline = ('''This is the {num} file
and the file path is
path: {path}
''')
with open('myfile.txt','w') as f:
    for i, path in enumerate(paths['file_paths'], 1):
        f.write(text_baseline.format(num=i, path=path))

【讨论】:

  • 我用的是python3.4那个版本支持字符串格式吗?
猜你喜欢
  • 1970-01-01
  • 2014-03-07
  • 2013-05-31
  • 2016-08-26
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多