How to convert numbers from a file into integers

the numbers in the file are alerady split but they are strings.

Doesnt anyone know how to convert them to integers so they can be manipulated as numbers.

Recommended Answers

All 2 Replies

You can cast them into integers using int().

For example, given a file full of numbers "file.num"

values = []
with open("file.num") as f:
  for line in f:
     for value in line.split():
        values.append(int(value))

print(values)

Of course this is not production quality since it doesn't handle files that have badly formatted integers. For that, you probably want a try block around the cast to int on line 5

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.