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

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.


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

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!