Search a string and print the line if it is found in python

91 views Asked by At

I'm a beginner in Python. I have a text file numberstofind.txt as follows:

-49

-56

-62

I need to find those numbers in another CSV file midvalues1.csv and print the line if they are found. Each number can't be on the same line. The problem is my script never finds the second number and I know it is in my CSV file.

import os
import csv
import sys

with open("numberstofind.txt", 'r') as fp: 
    data = ",{0}".format(fp.readline().strip())
    
with open("midvalues1.csv", "r") as csv:
    found = False
    for line in csv:
        if data in line:
            print(line)
            print('Found !')
            f = open("ident1.txt", "w+") 
            f.write(line)
            f.close()
            found = True

if not found: 
    print('Data not found!')
    
with open("numberstofind.txt", 'r') as pd:
    phrasedeux = pd.readlines()
    phrasedeux=phrasedeux[1]
    print(phrasedeux)
    
    with open("midvalues1.csv", "r") as csvd:
        found = False
        for line in csvd:
            if phrasedeux in line:
                print(line)
                print('Found !')
                f = open("ident2.txt", "w+")
                f.write(line)
                f.close()
                found = True
    
if not found: 
    print('Data not found!')
    
with open("numberstofind.txt", 'r') as ph:
    phrasetrois = ph.readlines()
    phrasetrois=phrasetrois[2]
    
    with open("midvalues1.csv", "r") as csv:
        found = False
        for line in csv:
            if phrasetrois in line:
                print(line)
                print('Found !')
                f = open("ident3.txt", "w+")
                f.write(line)
                f.close()
                found = True

if not found: 
    print('Data not found!')

Output:

876,6,-49,1754,John Doe

Found !
-56

Data not found!
411,6,-62,48,Some other name

Found !

-56 is the number that is never found.

What is the best approach to find each number of my text file into my CSV file and print the line?

I tried this:

import re
import csv

with open("numberstofind.txt", 'r') as d:
    dt = d.readlines()
    dt=dt[1]
    print(dt)

with open('midvalues1.csv', 'r') as csv:
    lines = csv.readlines()
    for line in lines:
        if re.search(r'-56', line):
            print(line)
            break

It works but I can't predict this number so if I replace -56 with dt

if re.search(dt, line):

This doesn't work anymore.

3

There are 3 answers

0
Vikas Sharma On BEST ANSWER

Taking text file numberstofind.txt as:

-49

-56

-62

and, CSV file midvalues1.csv as:

876,6,-49,1754,John Doe
411,6,-56,48,Some other name
411,6,-62,48,Some other other name

Try this:

import csv

with open("numberstofind.txt", 'r') as file:
    data = [line.strip() for line in file if line.strip() != '']

for i, number in enumerate(data):
    found = False
    with open('midvalues1.csv', 'r') as file:
        csv_reader = csv.reader(file)
        for row in csv_reader:
            if any(number in cell for cell in row):
                line = ','.join(row)
                print(line)
                print(f'Found {number}!')
                f = open(f'ident{i+1}.txt', 'w+')
                f.write(line)
                f.close()
                found = True

    if not found:
        print('Data not found!')

Output:

876,6,-49,1754,John Doe
Found -49!
411,6,-56,48,Some other name
Found -56!
411,6,-62,48,Some other other name
Found -62!

And, three new files are created with the names ident1.txt, ident2.txt, and ident3.txt containing the corresponding rows from the CSV.

0
John Gordon On

Open the numbers file once, and read each number into a list:

numberstofind = []
with open('numberstofind.txt') as f:
    for line in f:
        numberstofind.append(line.strip())

Then read the csv file line-by-line, and check if each number in the list is in the current csv row:

with open("midvalues1.csv", "r") as csv:
    for row in csv:
        for number in numberstofind:
            if number in row:
                print(f'{number}' was found in {row}')
0
Suramuthu R On

As per your program, you want to create a new file for every data found and the respective data to be written in the respective file. I'm following the same logic:

txt = open("numberstofind.txt", 'r')

#list of lines in numberstofind.txt
txt_data = txt.readlines()

#close txt_data to avoid data loss
txt.close()

csv = open('midvalues1.csv', 'r')

#list of lines in midvalues1.csv
csv_data = csv.readlines()

#close csv to avoid data loss.
csv.close()


#replace all commas with spaces in midvalues1.csv
for i in range(len(csv_data)):
    csv_data[i] = csv_data[i].replace(',', '    ')

#Iterate thru txt_data
for i, x in enumerate(txt_data):

    #Iterate thru csv_data
    for j, y in enumerate(csv_data):

        #found = False if not found
        found = 0
        if x in y:

            #found turns True if found
            found = 1
            print(y)
            print('Found !')

            #new_file's name should be ident{i+1}
            new_file_name = f'ident{i+1}'

            #create a new_file with the name given
            new_file = open(new_file_name, 'w')

            #write lines
            new_file.writelines(y)

            #close the file for saving
            new_file.close()

    #If not found print 'Data not Found'
    if found == 0:
        print(f'{x} is not found!')