-1

I am writing a text file with some of the data I analyzed using python. I am running into some error messages. Below is my code.

sixteen=0.1
fifteen=0.3
fourteen=-.4
fourteen_revised=1
thirteen=2

with open('TMV_AVD.txt','w') as f:
    f. write('16+',sixteen+'\n','15+', fifteen+'\n','14+',\
             fourteen+'\n','14-',fourteen_revised+'\n', '13-', thirteen)

What I want in my text file is the following

16+,0.1
15+,0.3
14+,-.4
14-,1
13-,2

The error message I get is the following.

ufunc 'add' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32').

I thought I understood with open function. Your suggestions will be greatly appreciated. Any suggestions?

jpp
  • 159,742
  • 34
  • 281
  • 339
user7852656
  • 675
  • 4
  • 15
  • 26

2 Answers2

2

It has nothing to do with open() and its context manager, it has to do with the concatenation of your data and mismatched types. Your example, tho, should throw a different error - I imagine the error you posted stems from some Pandas structure.

You can let str.format() attempt to concatenate your data as:

with open('TMV_AVD.txt', 'w') as f:
    f.write('16+,{}\n15+,{}\n14+,{}\n14-,{}\n13-,{}'.format(sixteen, fifteen, fourteen,
                                                            fourteen_revised, thirteen))

Or, if using Python 3.6+ you can directly build an f string:

f.write(f"16+,{sixteen}\n15+,{fifteen}\n14+,{fourteen}\n14-,{fourteen_revised}\n13-,{thirteen}")

Or you'll have to manually turn your data into a proper format before concatenating.

zwer
  • 24,943
  • 3
  • 48
  • 66
1

Your logic is overly complicated. I strongly recommend you use a list of tuples or OrderedDict to store your variables. Then use a simple for loop:

d = [('sixteen', ('16+', '0.1')),
     ('fifteen', ('15+', '0.3')),
     ('fourteen', ('14+', '-.4')),
     ('fourteen_revised', ('14-', '1')),
     ('thirteen', ('13-', '2'))]

with open('TMV_AVD.txt', 'w') as f:
    for _, vals in d:
        f.write(','.join(vals)+'\n')
jpp
  • 159,742
  • 34
  • 281
  • 339