从字典键创建具有不同名称的多个文本文件

huangapple go评论64阅读模式
英文:

Create multiple text files with distinct names from dictionary keys

问题

我正在尝试从字典中的每个键创建多个文本文件。

我已经进行了多次不成功的尝试。结果是文件被正确创建,但每个文件只写入最后一个键(Signal 8)。我不知道在哪里出错。

signals_dict = {'Signal 1': 1,
                'Signal 2': 1,
                'Signal 3': 1,
                'Signal 4': 1,
                'Signal 5': 1,
                'Signal 6': 1,
                'Signal 7': 1,
                'Signal 8': 1}

def to_string():
    count = 0
    while count <= len(signals_dict):
        count += 1
        for keys, values in signals_dict.items():
            with open(f'signal{count}.txt', 'w') as wf:
                wf.write(keys)

to_string()

输出结果:

从字典键创建具有不同名称的多个文本文件

从字典键创建具有不同名称的多个文本文件

英文:

I'm trying to create multiple text files from each key in a dictionary.

I have made several unsuccessful attempts. The result is that the files are produced correctly, but only the last key (Signal 8) is being written to every file. I don't know where I'm messing up.

signals_dict = {&#39;Signal 1&#39;: 1, 
                &#39;Signal 2&#39;: 1, 
                &#39;Signal 3&#39;: 1, 
                &#39;Signal 4&#39;: 1, 
                &#39;Signal 5&#39;: 1, 
                &#39;Signal 6&#39;: 1, 
                &#39;Signal 7&#39;: 1, 
                &#39;Signal 8&#39;: 1}


def to_string():
    count = 0
    while count &lt;= len(signals_dict):
        count +=1
        for keys,values in signals_dict.items():
            with open(f&#39;signal{count}.txt&#39;,&#39;w&#39;) as wf:
                wf.write(keys)

to_string()

Output:

从字典键创建具有不同名称的多个文本文件

从字典键创建具有不同名称的多个文本文件

答案1

得分: 1

只返回翻译好的部分:

"Are you just after a unique file name (based on the key) that contains the value? If so:

for name, value in signals_dict.items():
  with open(f"{name}.txt", "w") as fh:
    fh.write(str(value))
```"

<details>
<summary>英文:</summary>

Are you just after a unique file name (based on the key) that contains the value?  If so:

for name, value in signals_dict.items():
with open(f"{name}.txt", "w") as fh:
fh.write(str(value))


</details>



huangapple
  • 本文由 发表于 2023年2月18日 00:16:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定