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.
Taking text file
numberstofind.txtas:and, CSV file
midvalues1.csvas:Try this:
Output:
And, three new files are created with the names
ident1.txt,ident2.txt, andident3.txtcontaining the corresponding rows from the CSV.