简体   繁体   English

需要帮助搜索csv文件中的行是否包含单词

[英]Need help searching if a line in a csv file contains a word

I am writing some code. 我正在写一些代码。 I would like to have an if statement that if a row in the CSV file contains what you input (a single word) then it does something. 我想有一个if语句,如果CSV文件中的一行包含您输入的内容(单个单词),那么它将执行某些操作。

I have tried doing if row = input then do this but it doesn't work as the whole row does not = the input only part of it does. 我尝试过if row = input then do this但它不起作用,因为整个行不=输入仅一部分有效。

for row in reader:
    if row == input1:
        # Whatever I want

It does nothing, as the entire row does not equal input1 . 它什么也不做,因为整行不等于input1

您可以使用以下if input1 in row:

You can use 您可以使用

if row[0]==input1:

This will check if the first element in the row is equal to input1. 这将检查行中的第一个元素是否等于input1。

Maybe something like the following. 也许像下面这样。

with open('country.csv', 'r', encoding="utf-8") as myfile:
    data=myfile.readlines()

for line in data:
    if "Switzerland" in line:
        print(line)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM