Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a file as the default user input?

How do I read a whole file in python 3.6.x using the user input() function? Like the algorithms challenge sites do. For example:

  • I have a file with the following content:

    line 1
    line 2
    line 3
    end
    
  • My program would do something like:

    x = input()
    while x != 'end':
        print("I am at", x)
        x = input()
    
  • Then I would have as output:

    I am at line 1
    I am at line 2
    I am at line 3
    

I guess I need to wrap my python sample progam with another program (possible also python, or OS script) that call the first one passing the file as user input. But how could I do it?

like image 543
Adailson De Castro Avatar asked Feb 04 '26 05:02

Adailson De Castro


1 Answers

Usually such challenges will pipe the input via stdin, and expected the response via stdout.

To do that, run your command from a command line like so;

python program.py < input.txt

If you want to save the output of the script into a file, you can redirect it to one.

python program.py < input.txt > output.txt
like image 116
Shadow Avatar answered Feb 05 '26 20:02

Shadow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!