英文:
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 = {'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()
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论