问题
When i write to file my results:
output=knew[i][0],knew[i][1], knew[i][2],eigenval[k],group[i]
value=str(output)
o.write(value+'\n')
I get:
(0.05, 0.05, 0.166667, -0.8513056, 0.9881956035137526)
(0.05, 1.05, 0.166667, -0.8513056, 0.011652226336523394)
(0.05, -0.9500000000000002, 0.166667, -0.8513056, 0.00015217014972403685)
How to write to file so it doesn't add brackets?
回答1:
Instead of
value = str(output)
you can do
value = ', '.join(map(str, output))
What you see is the string representation of a tuple. It's there because you called str on it.
What the str.join method does is join an iterable (e.g. a tuple or a list) of strings, using the string that it's called on as a delimiter (here ', ' is the delimiter and map(str, output) is the iterable of strings.) into a single string. map applies a function to each element of an iterable. In this case, str is applied to each element of output, so that we have an iterable of strings, rather than float numbers.
Alternatively (a bit hacky) you can just strip off the parentheses from the value that you have:
value = str(output)[1:-1]
回答2:
You can also use the csv module:
import csv
with open('file.txt', 'wb') as f:
writer = csv.writer(f, delimiter=',')
output = knew[i][0], knew[i][1], knew[i][2], eigenval[k], group[i]
writer.writerow(output)
回答3:
value = "{0}, {1}, {2}, {3}, {4}".format(knew[i][0],knew[i][1], knew[i][2],eigenval[k],group[i])
o.write(value)
Using format function of str objects is a better approach. And more efficient too.
来源:https://stackoverflow.com/questions/20618640/how-to-write-to-file-without-parenthesis-in-python