My Python program requests some user input:
n = int(input())
for i in range(n):
s = input()
# ...
For debugging purposes, I would like to create a test input.txt file like this:
3
string1
string2
string3
so that I need not to manually enter data from the keyboard every time I launch it for debug.
Is there any way to get input()
from text file, not from keyboard (without changing program code).
I am using Wing Personal as a dev tool.
Update
I know for sure, that there exist bots which are able to test python programs passing various inputs and comparing output with known answers. I guess these bots do not hit the keyboard with iron fingers. Maybe they use command-line tools to pass input.txt
to the Python so that it reads input()
from that file, not from keyboard. I would like to learn how to do it.
I've noticed that none of these solutions redirects the stdin from Python. To do that, you can use this snippet:
import sys
sys.stdin = open('input.txt', 'r')
Hopefully, that helps you!
Input reads from Standard input so if you use bash you can redirect stdin to a file
without changing your code
in bash you would run something like
cat textfile | programm.py
or
< textfile programm.py
You can read the file into a list like this:
with open('filename.txt', 'r') as file:
input_lines = [line.strip() for line in file]
s would be data in index i.
n = int(input())
for i in range(n):
s = input_lines[i]
# ...
Make sure your py file is in the same dir as your txt file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With