Python I';我正试图把这些输入输入到一个文本文件中,

Python I';我正试图把这些输入输入到一个文本文件中,,python,function,text,area,Python,Function,Text,Area,在课堂上,我们学习计算正方形或矩形面积的函数。该程序要求输入一个人的名字,他们想要什么形状,长度和宽度是多少。然后它打印出该形状的区域,然后程序再次循环。我要做的是将每个单独的名称输入和区域输出到一个文本文件中。我们的老师没有说得太清楚怎么做。任何帮助都将不胜感激。代码如下: import time def area(l, w): area = l * w return area def square(): width = int(input("please ente

在课堂上,我们学习计算正方形或矩形面积的函数。该程序要求输入一个人的名字,他们想要什么形状,长度和宽度是多少。然后它打印出该形状的区域,然后程序再次循环。我要做的是将每个单独的名称输入和区域输出到一个文本文件中。我们的老师没有说得太清楚怎么做。任何帮助都将不胜感激。代码如下:

import time

def area(l, w):
    area = l * w
    return area

def square():
    width = int(input("please enter the width of the square"))
    squareArea = area(width, width)
    return squareArea

def rectangle():
    width = int(input("please enter the width of the rectangle"))
    length = int(input("please enter the length of the rectangle"))
    rectangleArea = area(length, width)
    return rectangleArea

def main():
        name = input("please enter your name")
        shape = input("please enter s(square) or r(rectangle)")
        if shape == "r" or shape =="R":
            print ("area =", rectangle())
            main()
        elif shape == "s" or shape == "S":
            print ("area =", square())
            main()
        else:
            print ("please try again")
            main()  
main()
编辑:对不起,我想我问的问题不够清楚。我希望能够输入一些东西,例如名称,并能够将其放入文本文件中

就是你要找的。行
file=open('file.txt','w')
创建了一个变量文件,其中存储了表示
'file.txt'
的file对象。第二个参数
w
,告诉函数以“写入模式”打开文件,允许您编辑其内容。。完成此操作后,只需使用
f.write('Bla\n')
写入文件即可。当然,用您想要添加的任何内容替换Bla,它可以是您的字符串变量。请注意,默认情况下,此函数不会在后面换行,因此如果需要,您需要在末尾添加一个
\n

重要提示:处理完文件后,请确保使用
file.close()
。这将从内存中删除该文件。如果你忘了做这件事,那就不会是世界末日,但你应该一直这样做。未能做到这一点是初学者程序内存使用率高和内存泄漏的常见原因

希望这有帮助

编辑:正如MattDMo提到的,最好使用
with
语句打开文件

打开(“file.txt”,“w”)作为文件:
#使用数据

这将绝对确保使用语句将对文件的访问隔离到此
。感谢MattDMo to提醒我这一点。

简易方法:

file_to_write = open('myfile', 'w') # open file with 'w' - write permissions
file_to_write.write('hi there\n')  # write text into the file
file_to_write.close()  # close file after you have put content in it
如果要确保文件在完成所有操作后关闭,请使用下一个示例:

with open('myfile.txt', 'w') as file_to_write:
    file_to_write.write("text")

您想从文本文件获取输入,还是想将输出发送到文本文件?将输出发送到一个文本文件,之后我可以在哪里看到该文件?处理文件I/o时,您应该始终使用
上下文管理器。
'file.txt'
将在与中创建的脚本相同的目录中创建。如果希望它位于其他位置,可以在脚本所在目录内的目录中指定文件,也可以指定计算机上任何文件的完整路径。创建此文件后,您可以像访问任何其他文本文件一样访问它。