简体   繁体   English

如何在 csv 文件中搜索特定字段然后在 Python 中打印整行

[英]How do I search for a specific field in a csv file then print the entire row in Python

I would include my whole program but it is too long so I will provide an example:我会包括我的整个程序,但它太长了,所以我将提供一个例子:

Say I had this csv file:假设我有这个 csv 文件:

John, 23, 1944, Africa
Fred, 45, 1922, China
Bob, 23, 1999, Japan

How do I search the file and print the row that 1944 is specifically in?如何搜索文件并打印 1944 所在的行? Essentially what I want it to do is find 1944, then print the whole row 1944 is in.基本上我想要它做的是找到 1944,然后打印 1944 所在的整行。

Also, if it's structured like另外,如果它的结构像

Name, Age, Year, Nation
John, 23, 1944, Africa
Fred, 45, 1922, China
Bob, 23, 1999, Japan

How would you print the found row plus the top row as well?你将如何打印找到的行加上顶行?

Many thanks.非常感谢。

Edit: Why is down voting necessary?编辑:为什么需要投反对票? I legitimately cannot find any information on this.我合法地找不到任何关于此的信息。 Therefore I have to ask.所以我不得不问。

This program answers your first question:该程序回答您的第一个问题:

import csv
import sys

with open('csv1.txt') as fp:
    reader = csv.reader(fp, skipinitialspace=True)
    writer = csv.writer(sys.stdout)
    writer.writerows(row for row in reader if row[2] == '1944')

And this answers your second question:这回答了你的第二个问题:

import csv
import sys

with open('csv2.txt') as fp:
    top_row = next(fp)
    sys.stdout.write(top_row)
    reader = csv.reader(fp, skipinitialspace=True)
    writer = csv.writer(sys.stdout)
    writer.writerows(row for row in reader if row[2] == '1944')

暂无
暂无

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

相关问题 如何从 python 中的 CSV 文件打印特定字段? - How do I print a particular field from a CSV file in python? 如何在列中搜索文本,然后使用该列使用 gspread 和 python 打印整行? - How do i search for a text in a column and then use that column to print the entire row using gspread & python? 如何使用python将包含特定单词的整行excel(.csv)复制到另一个csv文件中? - How to copy entire row of excel (.csv) which contain specific words into another csv file using python? 如何从 Python 中的 a.csv 文件中仅读取特定列和特定行? - How do I read only a specific column and a specific row from a .csv file in Python? 我如何获取python从CSV文件中删除搜索的行 - How do i get python to remove the row i search for from csv file 如何计算csv文件中的特定数据并在python中打印该数字? - How do I count specific data from a csv file and print that number in python? 我如何使用python在csv中搜索一行并将其放入另一个文件中: - how do i search for a row in a csv in python and putting it in a different file using this code: 如何在Python的CSV文件中找到特定项目的行号? - How do I find the row number for a specific item in a CSV file in Python? 如何从 python 的字段中提取特定数据进行打印? - How do I extract a specific data from a Field in python to print it? 如何使用多个搜索条件搜索CSV文件并打印行? - How to search CSV file with multiple search criteria and print row?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM