【问题标题】:Writing python dictionary items into separate txt files将python字典项写入单独的txt文件
【发布时间】:2021-08-30 05:46:26
【问题描述】:

我有一个看起来像这样的字典(每次都会生成):

{'Module1': [], 'Module2':['C:\\folder1\\folder2\\Module2\\Module2.1.c', 'C:\\folder1\\folder2\\Module2\\Module2.2.c', 'C:\\folder1\\folder2\\Module2\\Module2.3.c',  'Module3': ['C:\\folder1\\folder2\\Module3\\Module3.1.c', 'C:\\folder1\\folder2\\Module3\\Module3.2.c'], 'Module4': ['C:\\folder1\\folder2\\Module4\\Module4.1.c', 'C:\\folder1\\folder2\\Module4\\Module4.2.c', etc

所以它包含模块的名称和内部.c文件的路径。

为每个仅包含这些路径的单独 txt 文件制作单独的 txt 文件的最佳方法是什么?

所以举个例子,我应该有:Module1.txt 为空,然后 Module2.txt 包含:

'C:\folder1\folder2\Module2\Module2.1.c'
'C:\folder1\folder2\Module2\Module2.2.c'
'C:\folder1\folder2\Module2\Module2.3.c'

【问题讨论】:

  • 最佳方法:编写一个写入一个文件的函数,然后循环调用该函数。

标签: python json dictionary write


【解决方案1】:
#!/usr/bin/python
# -*- coding: utf-8 -*-

data = {
    'Module1': [],
    'Module2': ['C:\\folder1\\folder2\\Module2\\Module2.1.c',
        'C:\\folder1\\folder2\\Module2\\Module2.2.c',
        'C:\\folder1\\folder2\\Module2\\Module2.3.c'],
    'Module3': ['C:\\folder1\\folder2\\Module3\\Module3.1.c',
        'C:\\folder1\\folder2\\Module3\\Module3.2.c'],
    'Module4': ['C:\\folder1\\folder2\\Module4\\Module4.1.c',
        'C:\\folder1\\folder2\\Module4\\Module4.2.c']
}

def handleModule(filename, data):
    data = ["'%s'" % item for item in data]
    with open(filename, 'w') as f:
        f.write(' '.join(data))

for filename, module in data.items():
    handleModule(filename, module)

在主循环中,我们将遍历字典的所有键和值。对于每个键/值对(文件名/模块),都会调用 handleModule。

handleModule 函数开头有一个列表推导:["'%s'" % item for item in data]。它为每个列表项添加引号。

我们打开文件:with open(filename, 'w') as f:。它与f = open(filename, 'w') 做同样的事情,但保证文件在块结束后关闭。

' '.join(data) 将列表中的所有项目连接成一个字符串,使用空格字符作为分隔符。我们将这个字符串写入文件。

【讨论】:

  • 不鼓励仅使用代码的答案。请写出你做了哪些修改或者你是怎么写的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2020-08-26
  • 1970-01-01
  • 2022-08-22
  • 2021-10-12
  • 2018-06-28
相关资源
最近更新 更多