简体   繁体   English

将变量保存为文本文件名

[英]saving a variable as a text file name

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)

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.要求输入并将其作为文件名的变量传递。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM