2

我在使用 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

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

谢谢!

4

5 回答 5

7

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

FILE.close()
于 2012-06-26T01:15:59.783 回答
3

问题是您没有调用该close()方法,只是在最后一行提到它。您需要括号来调用函数。

Python的with声明可以使这变得不必要:

with open(filename,"w") as the_file:
    while i < 20:
        j = 0
        output = "square_sum = square_sum + "
        ...
        print(output)
        the_file.writelines(output)

with子句退出时,the_file会自动关闭。

于 2012-06-26T01:19:38.097 回答
2

尝试:

with open(filename,"w") as FILE:
    while i < 20:
        # rest of your code with proper indent...

不需要关闭...

于 2012-06-26T01:19:53.827 回答
1

首先,您的代码的 Pythonified 版本:

img = 'image_{i}_{j}'
avg = 'average'
clause = '{img}*{img} + {avg}*{avg} - 2*{avg}*{img}'.format(img=img, avg=avg)
clauses = (clause.format(i=i, j=j) for i in xrange(20) for j in xrange(20))
joinstr = '\n    + '
output = 'square_sum = {};'.format(joinstr.join(clauses))

fname = 'output.c'
with open(fname, 'w') as outf:
    print output
    outf.write(output)

其次,您似乎希望通过狂热的内联来加速您的 C 代码。我非常怀疑速度的提高能否证明你的努力是合理的,比如

maxi = 20;
maxj = 20;
sum = 0;
sqsum = 0;
for(i=0; i<maxi; i++)
    for(j=0; j<maxj; j++) {
        t = image[i][j];
        sum += t;
        sqsum += t*t;
    }

square_sum = sqsum + maxi*maxj*average*average - 2*sum*average;
于 2012-06-26T02:29:58.880 回答
0

看起来您的缩进可能不正确,但只是关于您的代码的一些其他评论:

writelines()将列表或迭代器的内容写入文件。由于您输出单个字符串,因此只需使用write().

lines ["lineone\n", "line two\n"]
f = open("myfile.txt", "w")
f.writelines(lines)
f.close()

要不就:

output = "big long string\nOf something important\n"
f = open("myfile.txt", "w")
f.write(output)
f.close()

另一方面,使用+=运算符可能会有所帮助。

output += "more text"
# is equivalent to
output = output + "more text"
于 2012-06-26T01:27:08.040 回答