Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当用户在个人程序中输入密钥并将其保存在新文件中时,如何保存数据_Python_Python 3.x - Fatal编程技术网

Python 当用户在个人程序中输入密钥并将其保存在新文件中时,如何保存数据

Python 当用户在个人程序中输入密钥并将其保存在新文件中时,如何保存数据,python,python-3.x,Python,Python 3.x,如何编写python程序,要求用户(3个用户)键入他们的信息,如姓名, 年龄、电子邮件和创建一个名为“personal_info.txt”的文件,其中包含所有信息 进入 示例输入 Enter name: A Enter age: 1 Enter email: keep data 3 times and keep in data 归档 a 10hero1@hotmail.com b 11hero2@hotmail.com c 12hero3@hotmail.com 我正试图这样做,但我不知道下

如何编写python程序,要求用户(3个用户)键入他们的信息,如姓名, 年龄、电子邮件和创建一个名为“personal_info.txt”的文件,其中包含所有信息 进入

示例输入

Enter name: A
Enter age: 1
Enter email: 
keep data 3 times and keep in data
归档

a 10hero1@hotmail.com

b 11hero2@hotmail.com

c 12hero3@hotmail.com

我正试图这样做,但我不知道下一步该怎么办

personal_file = open("data/personal_info.txt", "w")
for i in range(1, 4):
name = input("Enter your name : ")
age = int(input("Enter your Age : "))
email = input("Enter your Email : ")
code to keep data...

谢谢

您可以使用write或writelines将用户输入写入文本文件:

personal_file = open("personal_info.txt", "w")
for i in range(3):
    name = input("Enter your name : ")
    age = int(input("Enter your Age : "))
    email = input("Enter your Email : ")
    personal_file.writelines(f'{name}\n{age}\n{email}\n\n\n')
personal_file.close() 

如果我正确理解了你的问题,你不知道如何保存数据 从输入到文件中。实现所需的代码可以是 这:

强烈建议在处理文件时使用上下文管理器。 您还应该添加try-except块,因为使用用户输入很容易出错。

从a开始,然后查看
names, ages, emails = [], [], []
for _ in range(3):
    names.append(input("Enter your name : "))
    ages.append(int(input("Enter your Age : ")))
    emails.append(input("Enter your Email : "))
with open("data/personal_info.txt", "w") as f:
    for name, age, email in zip(names, ages, emails):
        f.write(name + age + email + '\n\n')