【问题标题】:I'm trying to put these inputs into a text file, [duplicate]我正在尝试将这些输入放入文本文件中,[重复]
【发布时间】:2017-05-25 12:50:30
【问题描述】:

在课堂上,我们正在研究计算正方形或矩形面积的函数。该程序询问一个人的姓名,他们想要什么形状以及长度和宽度是什么。然后它打印该形状的区域,程序再次循环回来。我要做的是获取每个单独的名称输入和区域并将它们输出到文本文件中。我们的老师没有说得太清楚如何做到这一点。任何帮助,将不胜感激。代码如下:

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

编辑:我觉得我问的问题不够清楚,抱歉。我希望能够输入一些东西,例如名称并能够将其放入文本文件中。

【问题讨论】:

  • 您想一个文本文件获取输入,还是希望将输出发送到一个文本文件?
  • 将输出发送到文本文件

标签: python function text area


【解决方案1】:

简单的方法:

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

【讨论】:

    【解决方案2】:

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

    重要提示:完成文件后,请务必使用file.close()。这将从内存中删除文件。如果你忘记了这样做,它不会是世界末日,但应该永远这样做。未能做到这一点是初学者程序中高内存使用和内存泄漏的常见原因。

    希望这会有所帮助!

    编辑:正如 MattDMo 所提到的,最佳做法是使用 with 语句打开文件。

    with open("file.txt", 'w') as file: # Work with data

    这将绝对确保对该文件的访问与此with 语句隔离。感谢 MattDMo 提醒我这一点。

    【讨论】:

    • 之后在哪里可以看到文件?
    • 在处理文件 i/o 时,您应该始终使用 with 上下文管理器。
    • 'file.txt' 将在与创建脚本的目录相同的目录中创建。如果您希望它位于其他位置,您可以在脚本所在目录中的目录中指定一个文件是,或者您可以指定计算机上任何文件的完整路径。创建后,您可以像访问任何其他文本文件一样访问此文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2017-07-09
    • 2022-11-27
    • 1970-01-01
    • 2014-10-01
    相关资源
    最近更新 更多