Is there any way to use a .txt as an input?

name = input("Whats your name?: ")

Can I use for example my .txt that is in the same directory on the input 'name'? I tried the code bellow /

    with open(name.txt, "r") as file:
        file.readlines()

But its not working :(

1 answer

  • answered 2020-03-25 14:12 GordonAitchJay

    It's a bit unclear what you want exactly. I think you want the variable name to be a name taken from a textfile.

    with open("name.txt", "r") as file:
       name = file.readline().strip()
    
    print(name)
    

    It works by opening up the file name.txt for reading as text, then it reads the first line, strip() is used to remove any spaces or newlines, and it is stored in the variable name.

    There is no need to call input().

    Be sure to read the tutorial on input and output.