首页 > 解决方案 > Python程序不会遍历整个输入文件

问题描述

编写一个程序,首先询问用户输入和输出文件的名称。假设输入文件每行有一个整数,程序应该在每一行写入输出文件:输入文件中的数字、它的平方、它的立方和用空格分隔的平方根。目前我被困在我的代码只读取输入文本文件的一行然后停止的地方。

def main():
    import math
    print("This program creates a file of Output numbers from a")
    print("File of input numbers")

    # Get the file names
    infileName = input("What file are the numbers in ? ")
    outfileName = input("What file should the new usernames go in ? ")

    #Open the files
    infile = open(infileName, "r")
    outfile = open(outfileName, "w")

    #Process each line of the input file
    for number in infile.readlines():
        #get the numbers from the line
        Num = float(number)
        #Square the number
        Square = (Num ** 2)
        #Cube the number
        Cube = (Num ** 3)
        #Squareroot of number
        Root = (math.sqrt(Num))
        #Write it to output file
        print(Root, ",", Cube, ",", Square, file = outfile)

    #Close both files
        infile.close()
        outfile.close()

        print("Numbers have been written to", outfileName) 

main()

标签: pythonlistfile

解决方案


在循环的每次(第一次)迭代期间关闭这两个文件。您需要删除一些空格,以便它们与 处于同一级别for,从而在循环之后发生。


推荐阅读