【问题标题】:How to write a function output into .txt file? [closed]如何将函数输出写入 .txt 文件? [关闭]
【发布时间】:2015-11-22 17:37:06
【问题描述】:

我必须编写一个生成随机(参数)整数的函数,我必须将此函数的随机输出写入 .txt 文件。我还必须从这个函数中找到最大和最小整数(也将它们写入 .txt)

我找不到任何关于这个主题的教程。想用“a+”作为作家。

【问题讨论】:

  • 您希望用什么语言编写函数?将其添加为标签..
  • 对不起,我忘了添加。 Python 2.7
  • 刚刚再次查看了您的问题 - 根本不清楚。这是作业吗?
  • 是的 完成下面的函数,它获取最小值、最大值和计数参数,并在最小值、最大值之间产生随机数,并将它们写入文件中。 import random def createRandomNumberFile(min, max, count, outputFileName): outputFile = open(outputFileName, "a+") for item in range(0, count): randomNumber = random.randint(min,max)
  • 请将您的代码放入问题中。否则不可读。

标签: function python-2.7 random output


【解决方案1】:

首先,请在线查看有关如何写入文件的教程。网上有大量免费资源。

你已经做了很多工作,只需要几行代码

import random 
def createRandomNumberFile(min, max, count, outputFileName):
    outputFile = open(outputFileName, 'a+')
    for item in range(0, count):
        randomNumber = random.randint(min,max) 
        outputFile.write(randomNumber)
    outputFile.close

说明 - 由于您已使用“a+”模式(附加模式)将文件分配给变量(输出文件),您可以简单地使用此变量写入文件,然后关闭文件(关闭文件不是总是必要的,但这是一种很好的做法)。

希望有帮助

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多