1

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?

3
  • 4
    By only one do you mean all of them are in the same line without any newline? In such a case you have to append a newline with each write to the file Commented May 3, 2012 at 8:11
  • 4
    instead of using xrange to iterate throught measurements you should just use for item in measurements or if you need the index for index,item in enumerate(measurements) Commented May 3, 2012 at 8:11
  • 2
    How about you show us some of your other code, maybe the contents of measurements? Commented May 3, 2012 at 8:14

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

Sign up to request clarification or add additional context in comments.

1 Comment

What you probably want is the "write-append" mode, a, not the "write-overwrite" mode, w.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.