# 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()
通过在写模式下打开
file
对象,可以将数据保存到Python中的文件中。为此,可以使用内置的open()
函数,它返回一个file对象。open()
函数接受许多可能的参数,但您感兴趣的两个参数是文件名和模式。作为用法示例:这将在写入模式中打开名为
your_filename_here.txt
的文件对象,通过传递"w"
作为函数的第二个参数来表示。从这里,您可以使用file
对象的write()
函数将用户名写入此文件:其中末尾的
\n
换行符确保每个用户名都被分配到文本文件中自己的行。你知道吗对
write()
函数的调用可以放入for
循环,将每个用户名写入文件。循环完成后,可以调用file
对象的close()
函数来关闭文件。你知道吗根据您对该计划的描述,作为一个原型,整个过程如下所示:
相关问题 更多 >
编程相关推荐