将变量保存为文本文件名

saving a variable as a text file name

我正在创建一个程序,该程序涉及将团队名称和统计信息存储到文本文件中,我想将该文本文件称为用户输入的团队名称。目前它可以工作,但所有团队都存储在一个文本文件中。

代码:

import random

def TheTeams (name):
with open("the_teams.txt, "a+") as t:
        t.write (name)
        t.write ("\n")
        
        
def NewPlayer (pname):
    at = int(input("enter your players attack 1-10 "))
    de = int(input("enter your players defence 1-10 "))
    if at >10:
        print ("NO")
        at = random.randint(1,5)
    if de >10:
        print ("NO")
        de = random.randint(1,5)
        

        
    with open("the teamss.txt", "a") as t:
        t.write (pname)
        t.write (" ")
        t.write ('%d' % at)
        t.write (" ")
        t.write ('%d' % de)
        t.write ("\n")

for i in range (1,7):
    pname = input("enter your players name ")
    NewPlayer (pname)
    
print ("""      Welcome to the ice hockey game
you will create your own team and try to score against your opponent
your teams are stored for future use

""")

n_team1 = input("player 1 do you want to create a new team ")

if n_team1 == "yes":
    team = input("enter your team name ")
    TheTeams (team)

您可以对玩家的名字做同样的事情。请求输入并将其作为文件名的变量传递。

这是你码哥的更新版本:

import random

def TheTeams (name):
  file_name = "./" + name + ".txt" # This is the code that will create the file

  with open(file_name, "a+") as t:
    t.write (name)
    t.write ("\n")
            
def NewPlayer (pname):
  at = int(input("enter your players attack 1-10 "))
  de = int(input("enter your players defence 1-10 "))
  if at >10:
      print ("NO")
      at = random.randint(1,5)
  if de >10:
      print ("NO")
      de = random.randint(1,5)
          
  with open("the teamss.txt", "a") as t:
      t.write (pname)
      t.write (" ")
      t.write ('%d' % at)
      t.write (" ")
      t.write ('%d' % de)
      t.write ("\n")

  for i in range (1,7):
      pname = input("enter your players name ")
      NewPlayer (pname)
        
print ("""      Welcome to the ice hockey game
you will create your own team and try to score against your opponent
your teams are stored for future use

""")
    
n_team1 = input("player 1 do you want to create a new team ")

if n_team1 == "yes":
    team = input("enter your team name ")
    TheTeams (team)