Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
程序运行时出错(Python)_Python - Fatal编程技术网

程序运行时出错(Python)

程序运行时出错(Python),python,Python,我的程序有问题,有人能帮我解决吗 目标: 在input.txt中: 7 12 100 Output.txt: 84 16 84是从7*12开始的,16是从100-84开始的 这是我当前的代码: with open('sitin.txt', 'r') as inpt: numberone = inpt.readlines()[0].split(' ') # Reads and splits numbers in the first line of the txt numbert

我的程序有问题,有人能帮我解决吗

目标:

在input.txt中:

7 12
100
Output.txt:

84 16
84是从7*12开始的,16是从100-84开始的

这是我当前的代码:

with open('sitin.txt', 'r') as inpt:
    numberone = inpt.readlines()[0].split(' ') # Reads and splits numbers in the first line of the txt
    numbertwo = inpt.readlines()[1] # Reads the second line of the txt file

product = int(numberone[0])*int(numberone[1]) # Calculates the product
remainder = int(numbertwo)-product # Calculates the remainder using variable seats

with open('sitout.txt', 'w') as out:
    out.write(str(product) + ' ' + str(remainder)) # Writes the results into the txt
它不输出任何东西。 有人能帮忙吗?
提前感谢任何人的帮助

想想发生了什么:

with open('sitin.txt', 'r') as inpt:
    # read *all* of the lines and then take the first one and split it
    numberone = inpt.readlines()[0].split(' ')

    # oh dear, we read all the lines already, what will inpt.readlines() do?
    numbertwo = inpt.readlines()[1] # Reads the second line of the txt file

我相信你可以用这个提示解决剩下的家庭作业。

当你调用
inpt.readlines()
时,你会完全阅读文件
sitin.txt
的内容,这样以后调用
readlines()
将返回一个空数组
[]

为了避免多次读取时出现此问题,您可以在第一次读取时将文件内容保存到变量中,然后根据需要分析不同的行:

with open('sitin.txt', 'r') as inpt:
    contents = inpt.readlines()
    numberone = contents[0].split(' ')
    numbertwo = contents[1]

product = int(numberone[0])*int(numberone[1])
remainder = int(numbertwo) - product

with open('sitout.txt', 'w') as out:
    out.write(str(product) + ' ' + str(remainder))

你收到错误消息了吗?@BenT我怎么看?当我打开它时,盒子消失得太快了,我看不到错误信息。哦!非常感谢你!所以我只是在定义numberone之后添加了另一个open('sitin.txt','r')作为inpt。谢谢你的帮助!