-3

I want to append following line to my text file:

Degree of polarization is 8.23 % and EVPA is 45.03 degree.

i.e. I want both string and numeric values to be appended.

I want to append above line with different numeric values after each run of my python code.

Any help will be appreciated.

For example

>>> a = 10.5 
>>> with open("myfile.txt","a") as f:
...  f.write(a)

gives me error.

atom
  • 153
  • 1
  • 9

2 Answers2

3

Do you mean something like this:

while True:
    polarization = getPolarization()
    evpa = getEvpa()
    my_text = "Degree of polarization is {} % and EVPA is {} degree.".format(polarization, evpa)

    with open("test.txt", "a") as myfile:
        myfile.write(my_text)

Maybe you should also write what have you tried yet and what problems/errors occurred

VRage
  • 1,458
  • 1
  • 15
  • 27
0

You can only write strings to files.

Strings can be concatenated:

>>> 'a' + 'b'
'ab'

Numbers can be converted to strings:

>>> str(4)
'4'

>>> str(5.6)
'5.6'

You should be able to get started with that.

Also, Python's string formatting will automatically do this for you:

>>> '{} % and {} degree'.format(6.7, 8.9)
'6.7 % and 8.9 degree'

Or with a more readable format using keywords:

>>> '{polarization} % and {evpa} degree'.format(polarization=6.7, evpa=8.9)
'6.7 % and 8.9 degree'
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • My question is NOT related to string formating. It is related to appending lines to text file. – atom Aug 13 '15 at 07:35
  • You can only write strings to files so you need to convert the values first. Your question isn't particularly clear. What difficulty do you have? – Peter Wood Aug 13 '15 at 07:39