无法将列表中的随机选项写入文本

2024-05-12 14:27:07 发布

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

我真的不确定什么在这里不起作用,我想让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不将随机选择写入文本文件?你知道吗


Tags: 文件nameimport名称列表namesrandom文本文件
2条回答

一个很好的实践是使用with,因为它隐式地包含了close方法:

with open('file.ext', 'w') as c1:
    c1.write(rand_name)

您的代码看起来很好,只是最后并没有实际调用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)

这样做可以确保文件在完成时关闭。你知道吗

相关问题 更多 >