I want to make the code which get the data from the text file with using input().
Concretely the file "tester.py" import the max.py and read the input.txt and,in someway the input data is pushed in the variable and the list of max.py. I want to make that tester.py
For instance,with below 2 codes.
input.txt
array1
2 4 6 2
with max.py
name=input()
array=list(map(int,input().split()))
print(name +" "+str(max(array)))
How do I implement it?.
In most system, you can also override 'standard input file' when executing a program, telling it to read from a file instead of from keyboard. That is often system-dependant and as I don't know which one is concerned here, this simple mention should do.
For example, in unix-like system, running bash: python max.py < input.txt
will run max.py after replacing standard input (file 0, the console) with input.txt
.
More generally, the >
operator can be use to redirect standard output, and <
to redirect standard input. If not using file name but opened file/pipe descriptor, prefix the descriptor with &
(eg python max.py <&64
, where 64 is the file descriptor.)
Hope that helps!
input.txt (locating at the same directory as max.py)
2 4 6 8 10 12 14
max.py
array = []
with open('input.txt', 'r') as file:
array = [int(item) for item in file.readline().split(' ')]
# print(array)
UPDATE #1
input.txt (locating at the same directory as max.py)
2 4 6 8 10 12 14
max.py
file = raw_input()
array = [int(item) for item in file.split(' ')]
# print(array)
command line
$ python max.py < input.txt
[2, 4, 6, 8, 10, 12, 14]
I do not think it is possible without open. Because you need to change the stdin in order to use input function.
import sys
with open('filepath', 'r') as file:
sys.stdin = file
line = input()
sys.stdin = sys.__stdin__
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.