【问题标题】:Facing problem to append text into a (file.txt) file in python面临将文本附加到python中的(file.txt)文件中的问题
【发布时间】:2020-10-22 08:53:54
【问题描述】:

如何在 python 中将文本附加到 (file.txt) 文件中

这是我的程序代码:

file = open("file.txt", "a")

aa = 10
bb = 1
cc = 12
xx = 20


try:
    if xx > aa:
        file.write("Yes xx is greater than aa")
        file.close()

    elif xx < aa:
        file.write("No xx is not greater than aa")
        file.close()


    if aa > xx:
        file.write("Yes aa is greater than xx")
        file.close()

    elif aa < xx:
        file.write("No aa is not greater than xx")
        file.close()


    if cc > xx:
        file.write("Yes cc is greater than xx")
        file.close()

    elif cc < xx:
        file.write("No cc is not greater than xx")
        file.close()
except Exception as e:
    print(e)

输出是:

我的问题是为什么只有第一个 if 和 elif 条件起作用并将该字符串写入文本文件,其余条件成功运行但字符串未附加到该文件中。

如果您能告诉我如何解决这个问题,我将不胜感激。

【问题讨论】:

  • 文件在第一次写入后关闭(即条件成功)。
  • 您应该在代码末尾关闭文件。

标签: python python-3.x append file-handling


【解决方案1】:

在向文件写入文本后,您将关闭该文件。如果您关闭该文件,您将无法再写入该文件,除非您再次打开它。 如果您使用with-statement,它将为您关闭文件。

试试这样的:

aa = 10
bb = 1
cc = 12
xx = 20

with open("file.txt", "a") as file:
    try:
        if xx > aa:
            file.write("Yes xx is greater than aa")
        elif xx < aa:
            file.write("No xx is not greater than aa")
        if aa > xx:
            file.write("Yes aa is greater than xx")
        elif aa < xx:
            file.write("No aa is not greater than xx")
        if cc > xx:
            file.write("Yes cc is greater than xx")
        elif cc < xx:
            file.write("No cc is not greater than xx")
    except Exception as e:
        print(e)

【讨论】:

    【解决方案2】:

    您的问题是您正在关闭文件,只要您第一次附加到它。删除file.close() 并最终只使用一次,将解决您的问题。还有一种更 Pythonic 的做事方式,就是使用 with open("file.txt", "a") as file: 这是您的代码的编辑版本:

    aa = 10
    bb = 1
    cc = 12
    xx = 20
    
    with open("file.txt", "a") as file:
    
        try:
            if xx > aa:
                file.write("Yes xx is greater than aa\n")
                
            elif xx < aa:
                file.write("No xx is not greater than aa\n")
                
            if aa > xx:
                file.write("Yes aa is greater than xx\n")
                
            elif aa < xx:
                file.write("No aa is not greater than xx\n")    
    
            if cc > xx:
                file.write("Yes cc is greater than xx\n")
                
            elif cc < xx:
                file.write("No cc is not greater than xx\n")
    
            file.close()
    
        except Exception as e:
            print(e)
    

    P.S \n 是换行符。这样会使输出更整洁。

    【讨论】:

      猜你喜欢
      • 2019-01-04
      • 1970-01-01
      • 2013-05-15
      • 2018-08-25
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多