我在这张桌子上遇到了一些麻烦:
import csv
with open('chill.csv','wb') as f:
writer = csv.writer(f)
for s in range(0,70,5):
for t in range(-25,10,5):
print 13.127 + 0.6215*t-11.362*s**0.16+0.396*t*s**0.16, '\t',
print
writer.writerow([13.127 + 0.6215*t-11.362*s**0.16+0.396*t*s**0.16])
问题是行和列的输入(s
和t
)直接被采用并详细说明到print
语句中,但我需要在两行中显示列这些结果派生的值。此外,我尝试使用常用命令将表导出到.csv文件,但Python给了我一个运行时错误:
ValueError: I/O operation on closed file
。我该如何解决这两个问题?
答案 0 :(得分:3)
你的代码需要在里面 with with block:
with open('chill.csv','wb') as f:
writer = csv.writer(f)
for s in range(0,70,5):
for t in range(-25,10,5):
print 13.127 + 0.6215*t-11.362*s**0.16+0.396*t*s**0.16, '\t',
print
writer.writerow([13.127 + 0.6215*t-11.362*s**0.16+0.396*t*s**0.16])
一旦你离开with
语句的正文,文件就会被关闭,所以writer.writerow
会因你看到的错误而失败。
如果您想要一行中的所有数据并打印出来:
with open('chill.csv', 'wb') as f:
import csv
wr = csv.writer(f)
data = ([str(13.127 + 0.6215 * t - 11.362 * s ** 0.16 + 0.396 * t * s ** 0.16)
for t in range(-25, 10, 5)]
for s in range(0, 70, 5))
for row in data:
print("\t".join(row))
wr.writerow(row)