将数据写入文件python

2024-05-16 21:14:24 发布

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

我的任务是: 写一个课外俱乐部的注册程序,它应该要求用户提供以下详细信息,并将其存储在一个文件中:名字,姓氏,性别和形式。你知道吗

以下是我目前的代码:

f= open("test.txt","w+")
first_name = input("Enter your First name>>>> ")
last_name = input("Enter your Last name>>>> ")
gender = input("Enter your gender>>>> ")

with open("test.txt", "a") as myfile:
    myfile.write(first_name, second_name, gender)

我已经创建了文件,但当我试图写入它时,我得到一个错误,说

myfile.write(first_name, last_name, gender)
TypeError: write() takes exactly 1 argument (3 given)"

Tags: 文件nametesttxtinputyouropengender
2条回答

由于write函数只接受一个字符串参数,因此必须将字符串附加到一个参数中,然后将其写入文件。不能同时将3个不同的字符串传递给myfile.write()

final_str = first_name + " " + second_name + " "+gender
with open("test.txt", "a") as myfile:
    myfile.write(final_str)

以下是write()方法的语法-

fileObject.write( str )

这意味着您需要将参数合并成一个字符串。你知道吗

例如:

myfile.write(first_name + second_name + gender)

也可以使用格式:

fileObject.write('{} {} {}'.format(first_name, second_name, gender))

相关问题 更多 >