Search code examples
pythondefaultstdin

Making a file as default stdin


I want to take input from a file by default. For example:

num=input()

This statement should take input from a file instead of waiting for key hits. I do not want to do it by redirecting standard input to a file, I want it by default. Simply, keyboard is default device for input, so instead of keyboard I want a file to give input.


Solution

  • You can attach your file to the standard input on the OS level like this:

    python script.py <input.txt
    

    To the script, it will seem like whenever input() is invoked, the user types the next line from the file.