Skip to content Skip to sidebar Skip to footer

Writing List Of Basic Variables To Text File

I want to write a text file that has some lines in the following format: result: variable1 +/- error1 result: variable2 +/- error2 And so on... So far I have: f = open('file_{a}.t

Solution 1:

If the problem is not the type of variable[i] or error[i],try this:

f = open('file_{a}.txt'.format(a=some_name), 'w')
for i in range(len(variable)):
   f.write('result: {0} +/- {1}\n'.format(variable[i],error[i]))

Solution 2:

From the documentation:

f.write(string)

writes the contents of string to the file, returning the number of characters written.

So you can't pass in any number of strings separated by commas as arguments. This is different to the way print() works which excepts any number of arguments and formats them for you...

So that is why you are getting the error:

TypeError: expected a string or other character buffer object

How to fix it:

Fixing it is really easy, if you are sure variable[i] and error[i] are strings, you can either:

format them with .format:

f.write('result: {} +/- {}\n'.format(variable[i], error[i]))

or concatenate them with the + operand:

f.write('result: ' + variable[i] + ' +/- ' + error[i] + '\n')

Hope this helps!

Post a Comment for "Writing List Of Basic Variables To Text File"