How to read numbers separated by hyphens in a text file?

Asked

Viewed 991 times

2

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 go saving each number this is separated by -?

  • Did you ever try anything? What was the difficulty found?

  • You can read the line as text and then use the function split("-")

  • I didn’t. I never actually used Python! But I arrived at this split solution. I will read the file as text, then split the string! Thank you very much.

2 answers

5

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 takes the file name as a parameter, opens it and reads it line by line. For each line, the numbers are separated by the hyphen character and converted to integer, returning the resulting list. So, to go through all the numbers of a file, just do:

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

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

See working on Repl.it

3

Use the code:

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

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

print(conteudo)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.