Home > Blockchain >  How to search list of numbers in many files
How to search list of numbers in many files

Time:05-07

I have 5 files containing numbers and need to search for a list of numbers and print the name of the file it has. i tried this code but don't work

import os 
 
out = open('output', 'w')                                                          
numbers = [23175,2080,6277,6431,19846,10330,25408,25811,8454,10515]
filenames = {
    'G':'green.txt',
    'R':'red.txt',
    'B':'blue.txt',
    'Y':'yellow.txt',
    'O':'orange.txt',
}
for k,filename in filenames.items():
    j=0
    with open(filename, 'r') as f:
        for line in f:
            if int(line.strip()) == numbers[j]:
                print(filename)
                print(numbers[j])
            else :
                j =1

i got

if int(line.strip()) == numbers[j]:
IndexError: list index out of range

CodePudding user response:

Try this:

numbers = [23175, 2080, 6277, 6431, 19846,
           10330, 25408, 25811, 8454, 10515]
str_numbers = [str(num) for num in numbers]
filenames = {
    'G': 'green.txt',
    'R': 'red.txt',
    'B': 'blue.txt',
    'Y': 'yellow.txt',
    'O': 'orange.txt',
}
for k, filename in filenames.items():
    with open(filename, 'r') as f:
        for line in f:
            num_line = line.strip()
            if num_line in str_numbers:
                print(f"{k}:{filename} => {num_line}")
  • Related