如何将.in文件作为python的输入

  • 本文关键字:python in 文件 python input
  • 更新时间 :
  • 英文 :


这是我的代码

def jumlah(A,B,C):
global result
result = A+B+C
count = 0
i = eval(input('input total test case: '))
while count < i :
A = eval(input('input A: '))
B = eval(input('input B: '))
C = eval(input('input C: '))
jumlah(A,B,C)
count = count + 1
print('case no'+str(count)+' : '+str(result))

如何放置外部文件进行输入,这样我就可以在不输入数字1乘1 的情况下进行测试

这是我在文件中输入的示例

2
1
2
3
2
3
4

第一行是病例总数,剩下的是A、B和C的输入。我的预期结果是

case no1 : 6
case no2 : 9

请帮忙。感谢

$ python my_file.py < my_input.txt

我想可以做到:(

您只需打开输入文件并读取即可,

with open("input.in", "r") as inputs:
for line in ins:
#your inputs one by one.

您应该将代码分解为执行您想要执行的操作的各个函数。在这种情况下,您可以提示用户是否要从文件中读取或手动输入。根据这个决定,您可以调用适当的函数。

def jumlah(A,B,C):
result = A+B+C
return result
def start():
option = input(' Would you like to: n'
' - (r) read from a file n'
' - (i) input(i) by hand n' 
' - (q) quit n ')
if option.lower() not in 'riq':
print('Invalid choice, please select r, i, or q.')
option = start()
return option.lower()
def by_hand():
count = 0
i = eval(input('input total test case: '))
while count < i :
A = eval(input('input A: '))
B = eval(input('input B: '))
C = eval(input('input C: '))
result = jumlah(A,B,C)
count = count + 1
print('case no'+str(count)+' : '+str(result))
def from_file():
path = input('Please input the path to the file: ')
with open(path, 'r') as fp:
cases = int(fp.readline().strip())
for i in range(1, cases+1):
a,b,c = fp.readline(), fp.readline(), fp.readline()
result = jumlah(A,B,C)
print('case no'+str(i)+' : '+str(result))
def main():
while True:
opt = start()
if opt == 'r':
from_file()
if opt == 'i':
by_hand()
if opt == 'q':
print('Goodbye.')
return
if __name__ == '__main__':
main()

最新更新