【问题标题】:how to make .in file as input for python如何将.in文件作为python的输入
【发布时间】:2018-12-12 04:05:38
【问题描述】:

这是我的代码

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 的情况下进行测试

这是我的示例 input.in 文件

2
1
2
3
2
3
4

第一行是案例总数,其余是A,B和C的输入。我的预期结果是

case no1 : 6
case no2 : 9

请帮忙。谢谢

【问题讨论】:

  • 一般来说,您不应该评估用户输入
  • 我想将我的输入转换为 int,我只是四处寻找并找到了 eval(input()),你知道如何在不评估的情况下做到这一点吗?谢谢
  • 使用int(input(...))
  • int(input(...)) 不起作用,它返回错误只能将 str(不是“int”)连接到 str

标签: python input


【解决方案1】:
$ python my_file.py < my_input.txt

我认为会这样做:)

【讨论】:

    【解决方案2】:

    您可以打开输入文件并阅读它,

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

    【讨论】:

    • 第一行应该是案例总数,所以它不应该包含在函数中。
    【解决方案3】:

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

    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()
    

    【讨论】:

    • woaaah 这确实有效,非常感谢。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多