Reputation: 1485
I am creating a file input.txt
to store my input and while running my py script file from cmd
. I want it to take input from that file, just like we can do something like that in c++.
a.exe < input.txt
How can we do something similar in python?
Upvotes: 1
Views: 4181
Reputation: 77377
Python works the same way. a.py < input.txt
and python a.py < input.txt
both work. You can read the file with sys.stdin
or the input()
function.
Upvotes: 5
Reputation: 15872
A simple input()
with < filename
would do:
for program:
x, y = input().split(',')
print(x, y)
In shell:
username:/home/path$ python test.py < input.txt
1 2
Upvotes: 0
Reputation: 14434
The line a.exe < input.txt
is a command to the shell. This method of running an executable will work regardless of what language a.exe
was written in.
To send the contents of intput.txt
to a python script, simply run it with
python a.py < input.txt
The contents of stdin may then be accessed via sys.stdin
.
For example, a.py
might read
import sys
contents = sys.stdin.read()
print(contents)
which will print the contents of input.txt
verbatim to stdout.
Upvotes: 0
Reputation: 1500
I think this is what you're looking for :
import sys
variable_string = sys.stdin.readline ()
print (variable_string)
Upvotes: 0
Reputation: 178
I hope this could help you to handle inputs in python from a textfile:
with open("File_name.txt", "r") as file:
for line in file:
#Do something with the line in the file
This link could help you.
Upvotes: 0
Reputation: 2017
With the main code ready to use once you extract the input, this is the code for doing the extraction of the input from input.txt:
with open("input.txt", "r") as file:
lines = file.readlines()
for line in lines:
storeInput = line
....
what ever the next piece of code would be to use the input from file.
So just working with the input.
Upvotes: 0