没有类的文本文件的字典

2024-10-01 02:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

这本词典叫做worterbuch.txt文件. 我可以用一个叫做沃特布赫.py你知道吗

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文件文件。你知道吗


Tags: 文件txtclose字典lineopendict文本编辑
1条回答
网友
1楼 · 发布于 2024-10-01 02:32:25

你很接近。试试这个:

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))

相关问题 更多 >