【问题标题】:Is It Possible to Make a File with a Function in Python?是否可以在 Python 中使用函数制作文件?
【发布时间】:2019-12-03 21:29:26
【问题描述】:

我正在尝试使用 python 中的函数创建一个文件,但我不知道如何。这就是我所拥有的,也是我需要的。

def file_maker():
  file_number = input("What number player are you? ")
  #Insert however you make a file in code, naming it ('inventory.' + filenumber + '.txt')

我只需要知道我将如何启动文件制作过程。我尝试用谷歌搜索它,但唯一出现的是如何访问不同文件中的函数。我是一名业余程序员,欢迎提出任何建议。感谢您的宝贵时间。

【问题讨论】:

  • 对您有所帮助的一件事是了解您可以在主程序中执行的任何操作,都可以在函数中以完全相同的方式执行。
  • 我使用 repl.it,我只用它的“制作文件”按钮制作文件。
  • 这被the tutorial覆盖了。
  • 直到现在我还没有访问过那个网站。

标签: python function file


【解决方案1】:
def file_maker():
  file_number = input("What number player are you? ")
  with open("inventory.%s.txt" % file_number, "w") as f:
    # Do whatever you need with the file using the 'f' to refer to the file object
    pass # in case you don't want to do anything with the file, but just create it

在此处阅读有关open 功能的更多信息:Open function

仅供参考,如果文件已经存在,这将覆盖该文件。

【讨论】:

    【解决方案2】:

    要创建文件,只需在写入模式下打开即可。 file_handle=open ('inventory.' + filenumber + '.txt', "w")

    file_handle 现在是一个对象,您可以使用各种方法将内容添加到文件中。阅读文档here

    请确保在使用file_handle.close()完成后关闭文件

    注意:尽管此方法有效,但通常认为使用with 是更好的做法,如the other answer 所示。它使用更少的代码并在完成后自动关闭文件。

    【讨论】:

    • 这回答了我的问题,但另一个答案更有效。对不起。
    • @PythonNerd 没关系,通常更好的做法是像其他答案一样使用with
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    相关资源
    最近更新 更多