嘿伙计们我是python的新手我是在11年级所以我还在学习我写了一个代码来循环询问用户姓名是什么年龄和年份组的问题然后打印出包含他们的用户名的用户名他们的名字的前三个字母和他们的年份组然后年龄? 我想知道如何将所有这些用户名写入文件我使用for循环重复问题5次询问5个不同的用户现在我想知道如何将他们的用户名存储到文件我知道如何存储输入但不是这类问题
答案 0 :(得分:0)
通过在写入模式下打开file
对象,可以将数据保存到Python文件中。为此,您将使用内置的open()
函数,该函数返回文件对象。 open()
函数接受许多可能的参数,但您感兴趣的两个参数是文件名和模式。作为用法的一个例子:
file = open("your_filename_here.txt", "w")
这将在写入模式中打开一个名为your_filename_here.txt
的文件对象,通过将"w"
作为函数的第二个参数传递来表示。从这里,您可以使用write()
对象的file
函数将用户名写入此文件:
username = "your_username_here"
file.write(username + "\n")
最后\n
换行符确保每个用户名都分配到文本文件中的自己的行。
然后可以将对write()
函数的调用放入for
循环,以将每个用户名写入文件。循环完成后,您可以调用close()
对象的file
函数来关闭文件。
file.close()
作为您对程序描述的原型,整个过程看起来像这样:
# Opens a new or existing file named "usernames.txt".
file = open("usernames.txt", "w")
# Assigns the number of users.
users = 5
# Loops once for each user.
for user in range(users):
# Collects user's name, year group, and age.
name = input("Enter your name: ")
year = input("Enter your year group: ")
age = input("Enter your age: ")
# Creates a username for the user.
username = name[0:3] + year + age
# Prints the username.
print("Username: " + username + "\n")
# Writes the username to the file.
file.write(username + "\n")
# Closes the file.
file.close()