0

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.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by griswolf
0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.