1

我不明白为什么我不能在我的 python 程序中写入文件。我有字符串列表measurements。我只想将它们写入文件。它只写入 1 个字符串,而不是所有字符串。我不明白为什么。这是我的一段代码:

fmeasur = open(fmeasur_name, 'w')
line1st = 'rev number, alg time\n'
fmeasur.write(line1st)
for i in xrange(len(measurements)):
    fmeasur.write(measurements[i])
    print measurements[i]
fmeasur.close()

我可以看到这些字符串的所有打印,但在文件中只有一个。可能是什么问题呢?

4

1 回答 1

6

The only plausible explanation that I have is that you execute the above code multiple times, each time with a single entry in measurements (or at least the last time you execute the code, len(measurements) is 1).

Since you're overwriting the file instead of appending to it, only the last set of measurements would be present in the file, but all of them would appear on the screen.

edit Or do you mean that the data is there, but there's no newlines between the measurements? The easiest way to fix that is by using print >>fmeasur, measurements[i] instead of fmeasur.write(...).

于 2012-05-03T08:08:56.990 回答