-2

I am hoping to create a system for my game where the user is able to save some of their information into a file; however, I am unsure if I would be able to name the file after the name they input. ("james" becoming "james.txt" would be an example of what I would like to happen)

import pygame
def playerSave(playerName):
  player = open("player1.txt", "w")
  player.write("test")
  player.close()
  playerLoad()
def playerLoad():
  player = open("player1.txt", "r")
  message = player.read()
  print (message)
  player.close()
playerName = "james"
playerSave(playerName)

I am unsure how to do this but the above code shows what I have so far.

Any help is much appreciated :)

sloth
  • 99,095
  • 21
  • 171
  • 219
  • 1
    Possible duplicate of [Which is the preferred way to concatenate a string in Python?](https://stackoverflow.com/questions/12169839/which-is-the-preferred-way-to-concatenate-a-string-in-python) – Aluan Haddad Feb 02 '18 at 09:59

2 Answers2

0

Perform a simple concatenation of the file extension with the input:

fileName = input("Player name: ") + ".txt"
player = open(fileName, "w")

If you want to be able to read these files after you restart the game, you might want to consider creating a 'master' text/data file which holds all of the players names, and then you can read the files back later.

AidanH
  • 502
  • 5
  • 24
0

I wouldn't do it that way. Because the point of saving the game is to load it at some point in the future, if you don't know the name of the player the next time he plays he will have to input the name again.

Do you want your player to input his name every time he plays? I would create some slots, and save each game in a different slot and then make the user select the slot.

Something like:

import os

slot = # Whatever way you think of asking the user what slot to load.
with open(os.path.join(ROOT_DIR, "saves", "slot") + slot + ".txt", "r") as f:
    data = f.read()
# You have your name in the file somehow
data = parse_load(data)
name = data.name
Jose A. García
  • 888
  • 5
  • 13