Python if语句不会为csv执行

时间:2018-06-03 12:26:13

标签: python csv if-statement conditional-statements

我正在尝试计算某个单词出现在csv文件中的次数。

import csv

path = r'C:\Users\Ahmed Ismail Khalid\Desktop\test.csv'
str = "line"
count = 0


with open(path,'rt',encoding="utf-8") as f :
    reader = csv.reader(f)
    for row in reader :
       print(row)
       if str == row[0] :
       count = count + 1

print("\n \n The count is :",count)

每当我运行代码时,我总是得到输出0的计数。但是,所有行都打印出来。我的csv文件有两列,id和text,数据如下:

id               text
1                this is line 1
2                this is line 2
3                this is line 3
4                this is line 4

你可以看到所有的行都包含str,而count应该是4,但它总是打印为0。

任何帮助都将不胜感激。

由于

3 个答案:

答案 0 :(得分:1)

指定'换行符' ,'分隔符'并且引用了char'准确地在打开csv文件时获得所需的结果。请参阅以下示例:

>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

答案 1 :(得分:0)

使用in查找字符串。

<强>实施例

with open(path,'rt',encoding="utf-8") as f :
    reader = csv.reader(f)
    for row in reader :
       print(row)
       if str in row[1] :
           count = count + 1

根据评论进行编辑

import csv
checkStr = 'line'
result = []
with open(path,'rt',encoding="utf-8") as f :
    reader = csv.reader(f)
    for row in reader :
       if checkStr not in row[1]:    #Check if 'line' not in row
           result.append(row)

with open(filename,'w') as f:        #Write new result. 
    writer = csv.writer(f)
    for row in result:
        writer.writerow(row)
  • 附加没有checkStr
  • 的所有行
  • 将结果写入新文件。

答案 2 :(得分:0)

import csv

count = 0
find = 'line'

with open('test.csv', 'rt', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        line = ', '.join(row)
        if find in line:
            count = count + 1

print('The count is :', count)

仅供参考:如果您想计算文件中出现的字数,可以避免加入。只需按行读取文件而不使用csv模块。