搜索字符串并打印该行(如果在 python 中找到)

问题描述 投票:0回答:1

我是Python的初学者。我有一个像这样的

txt
文件
numberstofind.txt

-49

-56

-62

我需要在另一个

csv
文件中找到这些数字
midvalues1.csv
并打印找到的行。每个数字不能在同一行。问题是我的脚本永远找不到第二个数字,我知道他在我的 csv 文件中。

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
# for
# with
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
# for
# with
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
            #sys.exit()
    # if
# for
# with
if not found: print('Data not found!')

输出:

876,6,-49,1754,John Doe

Found !
-56

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

Found !

-56
是从未找到的号码。

将 txt 文件的每个数字查找到 csv 文件并打印该行的最佳方法是什么?

我试过了

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

它有效,但我无法预测这个数字,所以如果我用

-56
 替换 
dt

if re.search(dt, line):

这不再起作用了。

python file numbers
1个回答
0
投票

打开数字文件一次,并将每个数字读入列表中:

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

然后逐行读取csv文件,并检查列表中的每个数字是否在当前csv行中:

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}')
© www.soinside.com 2019 - 2024. All rights reserved.