Parse txt file and return to another file - Python

Asked

Viewed 633 times

0

Good night!

There is a file with numbers, save in txt format, each number separated by space, with a list with about 50 values in each line of the txt file (and more than 10,000 lines in the file): 78 34 85 67 96 197 etc

I want to create a python program that compares 3 variables within the program with each line of the txt file. If the program reaches the end of all lines of the text file and does not find the 3 values, it will return the 3 search parameters in an output file, increments the variables in the loop and starts again.

For example, the program starts running with variables 30 31 and 32. It scans line by line. If you arrive at the end of the last line of the text file and you have not found the 3 values, return these values in an output file and resume parsing the text file with the value of one of the variables incremented. If you find the 3 values before the end line of the file, interrupt the search, increment the variable and resume the search on the first line of the file.

  • You can post the code you already tried and the specific problem you had that stopped you from reaching the end?

  • 5

    And it wasn’t as clear as the output that should be generated. You can create a [mcve], placing part of the file with the numbers, an example of the input and which should be the output?

1 answer

1

I solved the problem...

To read the file, I used: file_i = open(filename input, 'r')

I used the following instruction to store the file lines (as it will be necessary to read the same file several times):
entradatxt = file_i.readlines()

I created 3 repeat structures for using i, j and k counters:

nums = [i,j,k]  # objeto com os 3 índices para comparação com a linha do 
                # arquivo txt
for linha in entradatxt:
    lista = linha.rstrip().split(" ") #atribuição da linha a uma lista
    lista = list(map(int, lista)) #conversão dos valores para int
                          # pois estava dando erro na set(nums) & set(lista)
    ocorrencias = set(nums) & set(lista) #comparação lista e índices
    if (len(ocorrencias) != 0):
        break

    if (k==300):
        aprumando = str(sorted(nums)) #para ordenar os índices)
        aprumando = aprumando +"\n" #quebra de linha
        file_o.write(aprumando) #adicionando no arquivo saída
file_o.close()         

I’m sure there’s a way to simplify and make the execution better, but this way you’re meeting...

Thanks a lot, guys!

Browser other questions tagged

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