File write/read question

Chris Liechti cliechti at gmx.net
Tue May 14 21:11:07 EDT 2002


"Howard Roth" <hr at tngi.com> wrote in 
news:9diE8.1438$Ec.126265 at newsread2.prod.itd.earthlink.net:
> 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'

this executes arbitrary python code found in the file...
good enough for a quick hack but not suitable for production code due to 
security risks.
 
> "Nathan Hellmers" <nhellmers at yahoo.com> wrote in message
> news:78bc9697.0205130907.4288e607 at posting.google.com...
...
>> 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

well it was, but you throwed away the result...

"a = int(a)" would do what you want

>> 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.

if you want to get rid of whitespaces use strip(), lstrip(), rstrip()
these methods cut away whitspace on both or one side:
i.e. "a = a.rstrip()"

if the conversion with int() would have failed above, you would have get an 
exception. so the newline doesn't even matter in this case.

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list