Python 写入文件缺失行

标签 python python-3.x

我在使用 python 将字符串写入文件时遇到问题: (我想做的是使用 python 生成一些 C 程序) 我的代码如下:

filename = "test.txt"
i = 0
string = "image"
tempstr = ""
average1 = "average"
average2 = "average*average"
output = ""
FILE = open(filename,"w")
while i < 20:
    j = 0
    output = "square_sum = square_sum + "
    while j < 20:        
        tempstr = string + "_" + str(i) + "_" + str(j)        
        output = output + tempstr + "*" + tempstr + " + " + average2 + " - 2*" + average1 + "*" + tempstr        
        if j != 19:        
            output = output + " + "
        if j == 19:
            output = output + ";"        
        j = j + 1
    output = output + "\n"
    i = i + 1
    print(output)
    FILE.writelines(output)    
FILE.close

打印给了我正确的输出,但是 FILE 缺少最后一行并且缺少一些倒数第二行。将字符串写入文件有什么问题?

谢谢!

最佳答案

如果您调用该方法,可能会有所帮助...

FILE.close()

关于Python 写入文件缺失行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11199569/

相关文章:

python - 子类化 numpy ndarray 问题

python - pylint 警告 - 无法订阅的对象

python - 在 'for' 循环期间创建并写入新的 csv 文件

Python 3 - urllib.request - HTTPError

Python pandas dataframe 仅使用行信息而不是列 max min 标准化每一行

Python - 不支持的操作数类型 - : 'int' and 'str'

python - 在 csv 文件中查找模式

python - 使用子图时颜色条定位错误(matplotlib)

python - Tkinter:调度通过按钮单击执行的顺序线程

python - Wxpython 应用程序图标