You are not logged in.

#1 2007-06-02 08:00:54

twiistedkaos
Member
Registered: 2006-05-20
Posts: 666

Python, converting string to integer.

for my program, I am taking an integer and writting it as a string like so:

        f=open('save', 'w')
        #convert the number to a string.
        val = current_level_number
        s = str(val)
        if level == 1:
            f.write('0')
        else:
            f.write(s)
        f.close

now this works fine, then I want my program to open that file, and convert the string back to an integer so the program can use it again, I tried this:

    f=open('save', 'w')
    val=f
    s = int(val)
    level = s
    f.close

I get this error:

    int(val)
TypeError: int() argument must be a string or a number, not 'file'

any ideas of how to do this the correct way?

Last edited by twiistedkaos (2007-06-02 08:03:02)

Offline

#2 2007-06-02 08:17:23

bboozzoo
Member
From: Poland
Registered: 2006-08-01
Posts: 125

Re: Python, converting string to integer.

you need to read the number first, use

s = int(f.read())

Offline

#3 2007-06-02 09:32:50

twiistedkaos
Member
Registered: 2006-05-20
Posts: 666

Re: Python, converting string to integer.

bboozzoo wrote:

you need to read the number first, use

s = int(f.read())

I get this error with that:

    s=int(f.read())
IOError: [Errno 9] Bad file descriptor

Offline

#4 2007-06-02 11:00:51

iphitus
Forum Fellow
From: Melbourne, Australia
Registered: 2004-10-09
Posts: 4,927

Re: Python, converting string to integer.

look closely at the mode you opened the file with. are you writing, or reading it?

try,

f=open('save', 'r+')

instead

Last edited by iphitus (2007-06-02 11:01:21)

Offline

#5 2007-06-03 19:10:35

twiistedkaos
Member
Registered: 2006-05-20
Posts: 666

Re: Python, converting string to integer.

Alright thanks, works smile

Last edited by twiistedkaos (2007-06-03 19:11:30)

Offline

Board footer

Powered by FluxBB