3

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, @Shadow! I wish I could put you and @wim answers as correct. But I can't do it and he was faster. HAHAHA... My best!
Technically I was 3 minutes faster (mouse over the 'answered 1 hour ago' to see the timestamp :P But I don't mind either way.
Ops! You're right. To keep things fair I have set your answer as correct. Sorry for the mess, guys.
2

The usual standard lib tool for this job is the fileinput module:

import fileinput

for line in fileinput.input():
    print(f'working with line {line}')

Then from the shell, take your pick of the following (they all work):

$ python3 my_script.py my_file.txt
$ python3 my_script.py < my_file.txt
$ cat my_file.txt | python3 my_script.py

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.