【问题标题】:Dictionary to a text file without classes [duplicate]字典到没有类的文本文件[重复]
【发布时间】:2019-03-22 01:11:19
【问题描述】:

我刚开始学习 Python,我用文本编辑器创建了一个简单的字典

Spain Spanien
Germany Deutschland
Sweden Schweden
France Frankreich
Greece Griechenland
Italy Italien

字典名为 woterbuch.txt。我可以用一个名为 woterbuch.py​​ 的 python 程序来阅读它

woerter={}
fobj = open("woerterbuch.txt", "r")
for line in fobj:
    print(line)
fobj.close

这会将文本文件的内容作为输出提供。看起来很简单。有没有一种简单的方法来做相反的事情,即通过在 Python 中输入文本并告诉程序从中创建字典来创建文本文件?我试过的是

woerter={}
fobj=open("dict.txt", "w") 
woerter={"Germany", "Deutschland",
         "Italy", "Italien"} 
fobj.close() 

但这只会产生一个空的 dict.txt 文件。

【问题讨论】:

  • @JETM 说了什么,但更具体地说是Answer
  • “字典”这个词似乎在误导你。他的意思是一个实际的“字典”,而不是 python 数据结构 =)。

标签: python python-3.x


【解决方案1】:

你很亲密。试试这个:

woerter = ["Germany Deutschland", "Italy Italien"]
content = '\n'.join(woerter)

fobj=open("dict.txt", "w") 
fobj.write(content)
fobj.close() 

但我会采用更 Python 的方式,例如:

woerter = ["Germany Deutschland", "Italy Italien"]

with open("dict.txt", "w") as  fobj:
    fobj.write('\n'.join(woerter))

【讨论】:

  • 这正是我想要的。我很高兴它相当简单。非常感谢!
  • 然后考虑将此答案标记为正确。很乐意提供帮助。
猜你喜欢
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
  • 2023-03-18
相关资源
最近更新 更多