简体   繁体   中英

How to convert strings to integers in Python

I have code that converts an integer into a string to write it into a file, but the code to convert it back into an integer so I can put it through simple equations doesn't work.

my code: writing:

saveposx = open("sevedposx.txt", "w")
saveposy = open("sevedposy.txt", "w")
saveposx.write(str(x))
saveposy.write(str(y))

where x = 32 and y = 32 as well

reading:

readposx = open("sevedposx.txt", "r")
readposy = open("sevedposy.txt", "r")
posx = readposx.read(50)
posy = readposy.read(50)
actposx = int(posx)
actposy = int(posy)
actpos = ((actposx - 2), (actposy - 2))

x and y are defined outside a loop as to allow rewriting of x and y .

My code gives me this error:

  File "name_yet_to_come.py", line 399, in <module>
    actposx = int(posx)
ValueError: invalid literal for int() with base 10: ''

Thanks

The error message indicates that the file is empty. Probably the output file variable is still referenced / in the scope, or was not garbage collected yet.

Use

with open(...) as f:
    pass # do something with f here

to have the file automatically flushed and closed at the end of the scope.

Or just close them explicitly with f.close() , but consider using a try finally block then.

You can open multiple files in this scope, too, as further explained in How can I open multiple files using "with open" in Python? .

with open('a', 'w') as a, open('b', 'w') as b:
    pass # do something with a and b here

If you want to do IPC, then use a TCP stream or a Pipe() (or better yet: Queue() ) instead.

You have to close the file after writing to make sure that everything is saved. So for the writing part you should add the lines

saveposx.close()
saveposy.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM