如何使用python搜索csv文件中字符串的第一个单词来打印整个字符串(在单元格中)

2024-10-01 05:06:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我的csv文件中的每一行都有如下字符串。如果搜索字符串的第一个单词,则必须打印从该单词开始的相应字符串

EQPHHC_10    | 16912      | 0          | 0          | 0          | 53040      | 0          | 544        | 0          | 140643     | 0          | Any message

我试过这个密码。如果我的搜索词是“EQPHHC\u10”,那么它必须打印从EQPHHC\u10开始的整个字符串

所需o/p-

EQPHHC_10    | 16912      | 0          | 0          | 0          | 53040      | 0          | 544        | 0          | 140643     | 0          | Any message 
def find_index(input):
    o = open('PROCESS.csv', 'r') 
    myData = csv.reader(o) 
    index = 0 
    for row in myData:
      if row[0] == input:
        return index 
      else : index+=1
Row_num = find_index('EQPHHC_10')
print Row_num

Tags: 文件csv字符串messageinputindexanyfind
3条回答

试试这个:

import csv
def search_string(input_string):
    file = csv.reader(open('PROCESS.csv', 'r').readlines())
    for line in file:
        if line[0].strip() == input_string:
            print(line)

你很接近。您可以使用enumerate来查找索引

例如:

def find_index(input):
    with open('PROCESS.csv') as csv_file:
        reader = csv.reader(csv_file, delimiter="|") 
        for ind, row in enumerate(reader):
            if row[0].strip() == input:
                return ind
    return "N/A"                           #If input is not found. 

Row_num = find_index('EQPHHC_10')

你只需要读取文件和其中的行。找到索引,打印剩余的字符串

def find_index(input):
    fl = open('PROCESS.csv', 'r').readlines()
    for row in fl:
        if row.startswith(input):
            print row

find_index('EQPHHC_10')

相关问题 更多 >