How to read hyphen-separated numbers in a text file?

3

Let's say I have a text file where its configuration is:

1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20...-999

How do I read the file and save each number of the one that is separated by - ?

    
asked by anonymous 23.11.2017 / 18:31

2 answers

6

Use the code:

arquivo = open('teste.txt', 'r')

for linha in arquivo:
    conteudo = linha.split('-')

print(conteudo)
    
28.11.2017 / 02:49
4

If there is a possibility that the file has multiple lines, you can create the following generator:

def read(filename):
    with open(filename) as stream:
        for line in stream:
            yield map(int, line.split('-'))

It receives the file name as a parameter, opens it, and reads it line by line. For each row, the numbers are separated by the hyphen character and converted to integer, returning the resulting list. So, to go through all the numbers in a file, just do:

for numbers in read('numbers.txt'):
    for number in numbers:
        print(number)

The first for traverses all the lines of the file and the second all the numbers of each line.

See working at Repl.it

    
28.11.2017 / 03:07