python - 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()
解决方案
在循环的每次(第一次)迭代期间关闭这两个文件。您需要删除一些空格,以便它们与 处于同一级别for
,从而在循环之后发生。
推荐阅读
- python - Django - 带有多个文件的循环导入
- android - 如何从我的 POST 请求改造调用中获得对我的 Fragment 的响应
- visual-studio-code - Markdown 中的脚注:Jupyter 和 Google Colab
- html - 我如何将我的绿色按钮放在我的红色按钮旁边而不是在我的红色按钮下
- c# - 在 ASP.NET Core Web 应用程序上使用 Postman 模拟登录时出现 400 错误请求错误,其中单个用户帐户存储在应用程序中
- c# - 禁止状态 - 使用 Sendgrid 发送电子邮件时
- react-native-web - React Native Web 中的响应式图像?
- ios - Wkwebview cangoback 给出错误的结果
- node.js - 无法创建反应应用程序:npm 卡在“发现 0 个漏洞”
- oauth - Office 2019 (365) 中的 Outlook 未使用 oauth 连接到 gmail 或 google 公司帐户