Python Forum

Full Version: unexpected object?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
name = input("Your name, plz:")
file = "temp.txt"
with open(file, "w") as file:
    file.write(name + "\n")

file = "temp.txt"
while True:
    name = input("Your name, again:")
    if name == "":
        break
    else:
        with open(file, "a") as file:
            file.write(name + "\n")
When I input 3 names and it went wrong:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-44303ce02481> in <module>
10 break
11 else:
---> 12 with open(file, "a") as file:
13 file.write(name + "\n")

TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
---------------------------------------------------------------------------

But I really don't know where the syntax error is...
Does anyone help me solve this issue? Thank you very much.
Will be trouble if try to generate new file in each loop.
So have the making of file object outside of the loop,then write to file in the loop.
file_name = "temp.txt"
with open(file_name, "a") as file:
    while True:
        name = input("Your name, again:")
        if name == "":
            break
        else:
            file.write(f'{name}\n')
(Mar-08-2020, 02:29 PM)snippsat Wrote: [ -> ]Will be trouble if try to generate new file in each loop.
So have the making of file object outside of the loop,then write to file in the loop.
file_name = "temp.txt"
with open(file_name, "a") as file:
    while True:
        name = input("Your name, again:")
        if name == "":
            break
        else:
            file.write(f'{name}\n')

Got it, thank you. Smile