Forums

Read from file with input() in python3

Quite a few websites give you the ability to code your input in a file. This file this then read with input() in python3

I would like to use these small code snippets and run them in pythonanywhere.

Ideally I would like to have just to tick a field and put a text file somewhere which is then read from instead of stdin.

Since I didn't find this tick field what would be the minimal adoptions to input() (possibly something like fileinput)

to get my input from a file?

I'm a bit confused -- couldn't you just read the file in the normal way using open() and read() like this:

with open("filename.txt", "r") as f:
    data = f.read()

...? I figure I must be misunderstanding your question, because I'm pretty much certain you know how to do that :-)

[edit: dropped Stack Overflow link because it was confusing, replaced with example code]

Yes, of course this is not the problem. ;-) The question is to adopt already available files that use input() like hakerank.com with minimal efforts.

So in hakerrank.com I get an input field where I write my input into. This is then treated as stdin.

I am currently rewriting the code, so no problem here, but this would be a nice feature when using the editor.

Ah, I see! I wonder if you could use the mock library's patch function to replace input...?

That's a nice idea. I'll have a look at it. Thanks.

I'd love to hear if you come up with anything interesting using it!