Home > Back-end >  Iterating over numbers in a text file
Iterating over numbers in a text file

Time:10-29

I have a .txt file with 1,000 numbers that are only separated by a ','. When I open the file into python it reads it as one large string and therefore is only one line. I need to figure out a way to convert each number between the commas into an int so I can iterate over them. This is the code I have so far:

with open('HW5.txt') as f:
    data = f.read()
    print(type(data))
    newdata = data.replace(',',' ')
    data_seperate = newdata.replace(' ', '\n')
    print(data_seperate)
    print(len(data_seperate))
f.close()

It prints out each number on a new line, but the numbers are still strings and python counts each individual number as a character, not making each number a single integer. How do I deal with this? I am new to working with .txt files so the properties are confusing me. Trying to convert print(int(data_seperate)) returns this error:

ValueError: invalid literal for int() with base 10: '798\n441\n687\n780\n103\n405\n363\n66\n481\n171\n549\n449\n135\n229\n689\n248\n374\n697\n502\n209\n699\n684\n377\n235\n819\n471\n189\n43\n696\n999\n769\n501\n148\n474\n733\n729\n427\n710\n911\n207\n2

CodePudding user response:

With map:

with open("HW5.txt") as f:
    data = [*map(int, f.read().split(","))]

>>> data
[798, 441, 687, 780, 103, 405, 363, 66, 481, 171, 549, 449, 135, 229,
 689, 248, 374, 697, 502, 209, 699, 684, 377, 235, 819, 471, 189, 43,
 696, 999, 769, 501, 148, 474, 733, 729, 427, 710, 911, 207, 25, 785,
 855, 550, 481, 735, 832, 791, 970, 225, 559, 182, 922, 717, 723, 113,
 260, 166, 294, 97, 3, 323, 835, 18, 653, 876, 264]

CodePudding user response:

Here's one approach using str.split and map. Note that I'm using rstrip() here in case there's a trailing newline in the file, as we do have here.

sample_file_contents = """\
1,2,3,4,5,6,7,8,9
"""

num_list = sample_file_contents.rstrip().split(',')
numbers = list(map(int, num_list))

print(numbers)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Related