Search code examples
pythonwith-statementvalueerror

I Have a With-Statement That Defines Two Values, and It Is Giving Me a Value Error. Why, and How Do I Fix This?


This line of code is giving me

ValueError: unsupported format character 't' (0x74) at index 7

with open("inventory.%s.txt" % file_number, "w") as f, open("gold.%.txt" % file_number, "w") as g:

What does this mean, and how do I fix it?


Solution

  • I think it's trying to interpret the format string wrong - specifically, "%s.t". You can truncate numbers with similar syntax, which might be confusing the formatter.

    I recommend instead using either f-strings, if you're using python 3:

    with open(f"inventory.{file_number}.txt", "w") as f, open(f"gold.{file_number}.txt", "w") as g:
    

    or just the str.format() method otherwise:

    with open("inventory.{}.txt".format(file_number), "w") as f, open("gold.{}.txt".format(file_number) as g:
    

    which removes the ambiguity.