【问题标题】:python write to file not working inside functionpython写入文件在函数内部不起作用
【发布时间】:2017-07-15 08:54:57
【问题描述】:

我正在尝试在函数中编写基本的文件写入语法,但它不起作用。永远不会创建该文件。当我在函数之外执行它时,它工作正常。我不确定我做错了什么。请指点我正确的方向

def write():
    file=open("testfle.txt","w")
    file.write('hello')
    file.close()

    return

【问题讨论】:

    标签: python-3.x io


    【解决方案1】:

    我将您的代码保存在 IDLE 中名为 create.py 的文件中,然后通过调用您的方法 write() 运行它,当您调用方法 write() 时它可以工作,如下所示。

    它创建了一个名为 testfle.txt 的文件,内容为 hello

    def write():
        file=open("testfle.txt","w")
        file.write('hello')
        file.close()
        return
    
    ## call write
    write()
    

    在使用 Python 时还要注意缩进:)。

    【讨论】:

    • np,经常发生,然后我们认为:)!。请接受答案并投票!
    【解决方案2】:

    您可能将"testfile.txt" 输入错误为"testfle.txt"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多