2017-09-05 56 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) 
相關問題