命名文件并在Python中写入

2024-04-19 07:52:31 发布

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

我还在学习python,需要一些帮助-放松!你知道吗

我需要让用户命名要保存的文件,然后根据模型中存储的信息,使用文件中的一组信息写入文件。到目前为止,我可以创建一个文件名,但不能打开并写入其中:

file_name = input("please enter the name of the saved file:")
saved_file = file_name + ".txt"
file = open (saved_file, "w")
file.write(str(file_write))

文件写入在程序开始时预定义为:

file_write = "Generation ", new_gen ,"Juvenile population ", pop_j ,"adult population ", pop_a ,"senile population ", pop_s ,"total population ", pop_total

希望这有道理,记住…对我放松点!你知道吗

编辑-这不会产生错误。问题是文件已创建,但要写入其中的文本不会出现。你知道吗


Tags: 文件the用户name模型信息input文件名
1条回答
网友
1楼 · 发布于 2024-04-19 07:52:31

从您的消息中猜测(您应该始终包括您得到的输出,无论它是否是所需的输出或错误消息),我认为您的代码正在工作,但没有将所需的输出写入您的文件。你知道吗

这是因为您没有正确定义file_write。这样做的方式(用逗号分隔对象),file_write是一个元组(可以看到运行type(file_write))。你知道吗

相反,您应该:

file_write = "Generation {}, Juvenile population {}".format(new_gen, pop_j) 
# limiting myself to 2 values for concision

那么type(file_write)就是str,剩下的代码应该可以正常工作。你知道吗

相关问题 更多 >