ashim
ashim

Reputation: 25560

python. write to file, cannot understand behavior

I don't understand why I cannot write to file in my python program. I have list of strings measurements. I want just write them to file. Instead of all strings it writes only 1 string. I cannot understand why. This is my piece of code:

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()

I can see all print of these trings, but in the file there is only one. What could be the problem?

Upvotes: 1

Views: 310

Answers (1)

NPE
NPE

Reputation: 500167

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(...).

Upvotes: 6

Related Questions