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


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.

7 Years
Discussion Span
Last Post by snippsat

Se if this help.

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

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

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")


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
>>> 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
>>> finish = y.replace('e+',  '*(10**') + ')'
>>> finish

Or use a for loop.

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

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

My output--->

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

>>> y = math.sqrt( intensity / (1.327*(10**13)) )
>>> y
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.