我在使用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的最后一行缺失,而第二行的一些缺失。将字符串写入文件有什么问题?
谢谢!
答案 0 :(得分:7)
如果你打电话给方法,可能会有帮助...
FILE.close()
答案 1 :(得分:3)
问题是你没有调用close()
方法,只是在最后一行提到它。你需要parens来调用一个函数。
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
将自动关闭。
答案 2 :(得分:2)
尝试:
with open(filename,"w") as FILE:
while i < 20:
# rest of your code with proper indent...
不需要关闭...
答案 3 :(得分:1)
首先,代码的Python化版本:
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;
答案 4 :(得分: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"