Can't output Float values to text file using Python 3
-
21-12-2019 - |
Question
My code currently produces an array (ra) containing only float values. If a value in this array meets a certain condition, I want to output that specific value to a text file. Here is the part of my code in question:
outputFile = open('outFile.txt', 'wb')
i = 0
membersOuter = []
membersInner = []
membersCore = []
while i < (len(ra)):
DiffFinal = Diff[i] * 3600 * kpc_per_arcsec / 1000 #just converting values from an array called Diff
if DiffFinal < 2.0:
membersOuter.append(ra[i])
if DiffFinal < 1.0:
membersInner.append(ra[i])
if DiffFinal < 0.5:
membersCore.append(ra[i])
outputFile.write(ra[i] + ' ') #this is the part causing problems
i += 1
The code successfully creates arrays for the 3 member categories. However, I want to be able to output the ra values (which are all floats) meeting the final condition to outFile.txt. When I run this code I get the error:
TypeError: 'float' does not support the buffer interface
I am using Python 3.4, and searching past questions told me this process has changed since lower versions. Some changes that were recommended included:
outputFile.write(str(ra[i]))
TypeError: 'str' does not support the buffer interface
and
outputFile.write(bytes(ra[i]))
TypeError: 'float' object is not iterable
Solution
String formatting should help with both of your problems. Here is your example, with some irrelevant parts removed:
ra = [1.5, 2.1, 3.3, 11./7]
outputFile = open('outFile.txt', 'w')
for i in range(4):
outputFile.write('{} \n'.format(ra[i]))
Notice:
- The output text file is open for text, not binary,
w
, notwb
- The float variable is formatted by the
{}
directive inside the string. - The whitespace and newline are easily included in the format string.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow