Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 294
Nick Avatar asked Dec 03 '19 14:12

Nick


3 Answers

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!

like image 93
George Ogden Avatar answered Oct 16 '22 16:10

George Ogden


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
like image 39
Gorock Avatar answered Oct 16 '22 16:10

Gorock


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.

like image 1
Almog Avatar answered Oct 16 '22 15:10

Almog