Nick
Nick

Reputation: 3435

How to read input() from a text file in Python

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.

Upvotes: 13

Views: 41877

Answers (4)

George Ogden
George Ogden

Reputation: 815

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!

Upvotes: 9

do thuan
do thuan

Reputation: 475

You can create a test.py file which is used to run your test. In the test.py, you will read the content of input.txt and import the programming.

For example, in test.py file.

import main_code
with open('input.txt', 'r') as file:
   lines = file.readlines()

for line in lines:
   s = line

"""
working with the input.
""" 

Upvotes: 0

Gorock
Gorock

Reputation: 411

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

Upvotes: 22

Almog
Almog

Reputation: 27

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.

Upvotes: 1

Related Questions