简体   繁体   English

在python中,如何在txt文件中的特定列中搜索特定值,然后返回该特定值的行?

[英]In python, how can I search a specific column for a specific value in a txt file then return the specific value's row?

First of all, I have recently started studying python. 首先,我最近开始研究python。 So I am a beginner. 所以我是一个初学者。

1111  1  3  
1112  1  2  
1113  2  3  
1114  1  7  
1115  7  2  

Assume I have these values in the text file. 假设我在文本文件中有这些值。 As in the title, I want to search a specific column for a specific value in the txt file then return the specific value's row except for the searched "value". 就像标题中一样,我想在txt文件中的特定列中搜索特定值,然后返回特定值的行(搜索到的“值”除外)。

Example: 例:

Search the first column for 1113 value. 在第一列中搜索1113值。
Then return 2 3 as: 然后返回2 3为:

x = 2
y = 3

You could try this: 您可以尝试以下方法:

import sys
with open( filename, "r" ) as f:
    for line in f:
        parts = line.split(" ")
        if parts[0] == "1113":
            print("x={0} y={1}".format( parts[1], parts[2] ))
            sys.exit(0)

Try something like this: 尝试这样的事情:

with open('file.txt', 'r') as f:
    for line in f:
        if line.startswith('1113'):
            line = line.split()
            x = int(line[1])
            y = int(line[2])

as 'file.txt' put your file name and as '1113' put the value you are looking for. 'file.txt'您的文件名,如'1113'输入您要查找的值。 good luck 祝好运

There is a csv module which will do all the dirty work for you: 有一个csv模块可以为您完成所有肮脏的工作:

import csv

def find(filename, number):
    with open(filename) as file:
        reader = csv.DictReader(file,
                                fieldnames=['col1', 'col2', 'col3'],
                                delimiter=' ')
        for line in reader:
            if line['col1'] == str(number):
                return (line['col2'], line['col3'])

if __name__ == '__main__':
    (x, y) = find('data.txt', 1113) or (None, None)
    print(x, y)

I'd prefer: 我更喜欢:

search_text = '1113'
with open(FileName) as f:
    for i in f:
        if i.strip() != '':
            for j in i.strip().split():
                if j[0] == search_text:
                    x = int(i[1])
                    y = int(i[2])

This will allow you to search for any value on any column. 这将允许您在任何列上搜索任何值。

import csv


def find(reader, col, val):
    for row in reader:
        if row[col] == val:
            return row
    raise ValueError('Value {} not found in row {}'.format(val, col))


def findexcept(reader, col, val):
    r = find(reader, col, val)
    r.pop(col)
    return r

with open('searchdata.txt') as f:
    lines = (line.strip() for line in f)
    c = csv.reader(lines, delimiter=' ', skipinitialspace=True)

    try:
        x = findexcept(c, 0, '1114')
        print(x)
    except ValueError as ve:
        print('Error: {}'.format(ve))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何更改txt文件Python中特定列的行值? - How to change the value of a line in specific column in a txt file Python? 使用 Python 在特定列中搜索特定值 - Search for a specific value in a specific column with Python 如何编写 Python 代码来查找特定行值的 Pandas DF 中列的值的总和? - How can I write the Python code to find the sum of values of a column in a Pandas DF for a specific row value? 如何在Python中添加到.txt文件中特定字符串的行? - How do I add to the row of a specific string in a .txt file in Python? 如何在整个数据框中搜索特定值并返回其列和行索引 - How to search a specific value in the whole dataframe and return its column and row indexes 如何在Python中的CSV文件中搜索特定元素并在其下方打印其值 - How can I search a specific element and prints its value beneath it in a CSV file in Python 如何从 Python 中的 txt 文件中计算特定数字的值? - How to compute the value of specific numbers from a txt file in Python? 使用 Python 从 csv 文件中的特定行号和列号获取值 - Getting a value from a specific row and column number in a csv file with Python 如何在 Python 中为 YAML 文件的特定键添加值? - How can I add a value to a specific key to a YAML file in Python? 获取列中具有特定值的最后一行,Python - Get last row with specific value in column, Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM