Home > Software engineering >  saving a variable as a text file name
saving a variable as a text file name

Time:01-23

I'm creating a program that involves storing a team name and stats to a text file and i want to call the text file the name of the team that the user enters. At the moment it works but all teams are stored to a single text file.

code:

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)

CodePudding user response:

You can just do the same thing you've done for the player's name. Ask for input and pass it in as a variable for the file's name.

CodePudding user response:

This is the updated version of your code brother:

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)
  •  Tags:  
  • Related