真的不确定这里有什么不起作用,我希望python从列表中选择一个随机名称,这是因为我打印了变量。
然后我想将随机名称存储在文本文件中。文件在那里,但它只是空的。任何帮助将不胜感激。
import random
names = "Balo", "Bandugl", "Baroro", "Cag", "Charoth", "Duglinglabat", "Dulko", "Fangot"
rand_name = random.choice(names)
c1= open( "character_one.txt", "w")
c1.write(rand_name)
c1.close
为什么python没有将随机选择写入文本文件?
答案 0 :(得分:4)
您的代码看起来很好,除非您最后没有实际调用c1.close
。
您需要在其后添加()
来执行此操作:
import random
names = "Balo", "Bandugl", "Baroro", "Cag", "Charoth", "Duglinglabat", "Dulko", "Fangot"
rand_name = random.choice(names)
c1 = open("character_one.txt", "w")
c1.write(rand_name)
c1.close()
这就是使用with-statement打开文件的好主意:
import random
names = "Balo", "Bandugl", "Baroro", "Cag", "Charoth", "Duglinglabat", "Dulko", "Fangot"
rand_name = random.choice(names)
with open("character_one.txt", "w") as c1:
c1.write(rand_name)
这样做可确保在完成后关闭文件。
答案 1 :(得分:1)
一个很好的做法是使用with
,因为它隐含地包含close
方法:
with open('file.ext', 'w') as c1:
c1.write(rand_name)