Jump to content

Reading integer from a file

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
your_rock

your_rock

    Newbie

  • Members
  • Pip
  • 8 posts
Hello, I have a problem while reading numbers from a text file. Let's say I have

1 14 25 12 9 6

written in a text file, and I want python to read those numbers as integers. So when I read and make a list by splitting them [1, 14, 25, 12, 9, 6] I wanna use these numbers for addition/substraction, but Python reads them as str, not int. How to make it read them as integers? Thanks.

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
You use int():
theFile = open("filename.txt", "r")
theInts = []
for val in theFile.read().split():
    theInts.append(int(val))
theFile.close()
Then just use theInts.
Wow I changed my sig!

#3
your_rock

your_rock

    Newbie

  • Members
  • Pip
  • 8 posts
Thank you very much, it is working now. :)