File write/read question

Howard Roth hr at tngi.com
Tue May 14 20:45:57 EDT 2002


One way to do the conversion is to use 'eval(a)'
So 'print eval(a) + eval(a)" will give you two.
Or you can assign 'x = eval(a)' and 'print x + x'


"Nathan Hellmers" <nhellmers at yahoo.com> wrote in message
news:78bc9697.0205130907.4288e607 at posting.google.com...
> Hi,
>
> I'm just getting started with Python, and am stumped on a basic
> problem.  I have one program that runs a lot of calculations and
> produces an integer.  I want to write that integer to a file, and then
> read it with another program to run some more calculations.  I know
> that an integer written to a file is actually a string, but how do I
> convert the string to an integer once I have read it with program #2?
>
> Simplified example of what I am trying to do:
>
> ---------------
> #1
>
> test = open("test.txt", "w")
> a = 1
> print >> test, a
> test.flush()
> ----------------
>
> That successfully writes the number 1 to a file called test.txt.
>
> ----------------
> #2
>
> test2 = open("test.txt", "r")
> a = test2.readline()
> int(a)
> print a + a
> ----------------
>
> That successfully reads the number 1 from the file and assigns the
> variable "a" to it, but the printout is 1 1 (on two lines) rather than
> 2.  Using type I can see that "a" was not converted to an integer.  I
> can also see that "a" actually equals "a\n".  If I slice off the \n
> with "a = a[0:1]", I still can't convert it to an integer.
>
>
> Any help would be greatly appreciated.
>
>
> Thanks,
>
> Nathan
>





More information about the Python-list mailing list