1

So I'm writing a very simple saving system for my game, and it keeps saving the file name as simply the variable name (before the addition of the ":MinecraftText-turePack.txt"). I ran a print through it (after the name change), and the variable was changed, but it still gave me the wrong file name. Any thoughts? Thanks.

if response == "save_pack":
    print("What do you want to call it?")
    name = input()
    name = name + ":MinecraftText-turePack.txt"
    pack = open(name, "w")
    for each in inventory:
        name, amount, recipe = each
        pack.write(name)
   pack.close()

Edit: Possibly another important detail; it is creating a file, just with the wrong name

Griftor
  • 91
  • 1
  • 6

3 Answers3

1

From the print statement used as a function I'll assume we're working with Python 3. Moving the prompt is optional, but removes a line of code. Also, just for clarity, I've renamed the second name variable to pname and started a new variable for the filename called fname. This way you can check each one. Also try taking out the colon in the file name (as Michael suggested)

if response == "save_pack":
    name = input("What do you want to call it?\n")
    fname = name + "-MinecraftText-turePack.txt"
    pack = open(fname, "w")
    for each in inventory:
        pname, amount, recipe = each
        pack.write(pname)
   pack.close()

Although this answer is slightly more clear, your original example ran from a linux prompt just fine. Most non-unix systems don't like : in file names. Here is some background for Windows in particular.

Community
  • 1
  • 1
Gabriel
  • 10,524
  • 1
  • 23
  • 28
  • It doesn't seem to recognize raw_input as a valid command. The exact error is: NameError: name 'raw_input' is not defined – Griftor Jul 28 '14 at 06:09
  • sorry, looks like you're using Python 3 and `raw_input` is not there anymore. What happens if you break up the variables so we can test each one. For example `name = input()`; `fname = name + ":Minecra..."` – Gabriel Jul 28 '14 at 06:14
1

I'm assuming you're using Windows. You have a colon (:) in your file name. That is a reserved character, and actually specifies a file stream.

File Streams

Try using a different character in the name.

Keith
  • 42,110
  • 11
  • 57
  • 76
0

If you're using python-dotenv or any library which imports and overwrites local variables with the environment, the variable name in your top level module will be overwritten by os.environ['name'] which is the hostname of the machine running the python intepreter. If you didn't set a hostname, it'll be an empty string and therefore name == ''.

If you want to make sure that this is what's happening, try to set variable names like shell, pwd, user, etc. on Linux and homepath, appdata, windir, etc. on Windows and see if they're overwritten.

Iuri Guilherme
  • 389
  • 1
  • 10