2017-09-05 59 views
0
whichgender=input("Would you like to view male or female students? ") 
if whichgender == "Male": 
    with open('classinfo.csv' , 'r') as classinfoReport: 
     classinfoReaders = csv.reader(classinfoReport) 
     for row in classinfoReaders: 
      for field in row: 
       if field == whichgender: 
        print (row) 

我想从包含单词'男'的csv文件中打印每一行。此代码的工作原理,但它只打印它找到的单词男性在第一行。我的文件中有13行与'男'在他们,我想打印他们所有。我该怎么做?Python-如何使用csv文件中的常见单词打印多行?

+0

请提供的几行输入例如,它会帮助找到你的代码有什么问题 – Vinny

+0

如果我的建议解决了你的问题,将其标记为答案将不胜感激。谢谢。 –

回答

1

我建议你使用pandas来简化问题。

import pandas as pd 
df = pd.DataFrame(pd.read_csv('classinfo.csv', header=None)) 
print(df[df[<index of the gender string here>] == 'Male']) 

我写了相同的文件名的虚拟CSV文件作为你classinfo.csv

Adam,Male,25 
Milo,Male,34 
Mikka,Female,20 
Samantha,Female,19 
John,Male,21 

由于性别指数1

import pandas as pd 
df = pd.DataFrame(pd.read_csv('classinfo.csv', header=None)) 
print(df[df[1] == 'Male']) 

结果运行时:

 0  1 2 
0 Adam Male 25 
1 Milo Male 34 
4 John Male 21 
0

或者你可以在你的代码

whichgender=input("Would you like to view male or female students? ") 
if whichgender == "Male": 
    with open('classinfo.csv' , 'r') as classinfoReport: 
     classinfoReaders = csv.reader(classinfoReport) 
     for row in classinfoReaders: 
      if 'Male' in row: 
       print(row) 


我的建议更改以下使用也pandas

0

这是你所需要的: -

whichgender=input("Would you like to view male or female students? ") 
if whichgender == "Male": 
    with open('classinfo.csv' , 'r') as classinfoReport: 
     classinfoReaders = csv.reader(classinfoReport) 
     for row in classinfoReaders: 
      for field in row: 
       if whichgender in field: 
        print (row) 
相关问题