Sorry for my second newbie question....well now I am dealing with a text file that has the following line:

1e+12


Anyways, so I want to go into the file (named intens.txt) and replace the "e+" so that the line will look like this : 1*(10**12) .....The line will be changing so it's never going to be the same exponential, but it's always in the same format. How do i make it so i can change it to the format that python takes so i can use it for mathematical operations? So pretty much I want to ALWAYS replace "e+" with " *(10** " and add a closing parenthesis ")" at the end of the line. Once it is modified, i just want to go in the file and read the new modified line and store it back in python on a variable.

Recommended Answers

All 5 Replies

Se if this help.

>>> a = '1e+12'
>>> a
'1e+12'

>>> b = a.replace('e+',  '*(10**') + ')'
>>> b
'1*(10**12)'

Not quite, this is what i have but it gives me the following error on the g.write(f) line
TypeError: argument 1 must be a string or read-only buffer, not list

g = open("file.txt", 'r')
f = g.readlines()

for i in range(len(f)):
    if "e+" in f[i]:
        f[i] = f[i].replace("e+", "*(10**").replace("\n", ")\n")

g.write(f)
g.close()

TypeError: argument 1 must be a string or read-only buffer, not list

readlines()--> return a list.
Convert list to sting.

>>> my_file = open('test1.txt', 'r')
>>> x = my_file.readlines()
>>> x
['1e+12']
>>> type(x)         # use this to find out what datatype you are dealing with
<type 'list'>
>>> y = ''.join(x)  # list to string
>>> type(y)
<type 'str'>
>>> y
'1e+12'
>>> finish = y.replace('e+',  '*(10**') + ')'
>>> finish
'1*(10**12)'

Or use a for loop.

my_file = open('test1.txt', 'r')
x = my_file.readlines()

for item in x:
    item
    
finish = item.replace('e+',  '*(10**') + ')'
print finish

'''
My output--->
1*(10**12)
'''

Snippsat, thanks so much....i actually got it working right before you posted. Well, now when i am trying to use that piece of information on a calculation it gives me an error, it tells me "invalid literal for float()

I saved the 1*(10**12) to a variable named intensity.

Now when i do the following calculation:

y = sqrt( intensity / (1.327*(10**13)) )


I tried writing it like this too:

y = str( sqrt( float( intensity) / (1.327*(10**13))))

but it still doesn't work.

How can i use intensity in that calculation?

import math

>>> intensity = 1*(10**12)
>>> intensity
1000000000000L

>>> y = math.sqrt( intensity / (1.327*(10**13)) )
>>> y
0.27451402562301408
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.