2017-04-13 220 views
2

我必須編寫一個代碼,它需要一個csv文件並提取與來自泰坦尼克號的乘客數據相關的數據。我需要從這個文件中提取一個新文件,其中包含第三課中倖存的乘客(僅此)和頭文件。CSV文件寫入,需要寫入特定的行到新的csv文件

我已經提供了我迄今爲止編寫的代碼(文本)。它適用於測試案例(它打印#5),但我相信我的target_data_file是空的?

我在尋找如何將這些特定行寫入我的target_data_file。我認爲它應該是沿着一個for循環 如果survived == str(1) and pclass == str(3),寫入Target_data_file

雖然不確定!

謝謝!

import csv 
from copy import deepcopy 

def third_survived(source_data_file, target_data_file): 
    """(str, str) -> int 
    Input: Source data is the name of a .csv file containing a subset of the 
    Titanic passenger data, and target_data, the name of a new csv file to be 
    created. 
    Output: This function will create a new .csv file named target_data_file and 
    write in it the lines from source_data_file that correspond to the third class 
    passengers who survived the sinking. The function returns the number of lines 
    written to target_data_file. 

    >>>third_survived('titanic_some.csv', 'titanic_target.csv') 
    5 
    """ 

    with open (str(source_data_file), 'r') as file: 
     data_reader=csv.reader(file) 
     data_orig=[] 
     for row in data_reader: 
      data_orig.append(row) 

    count= 0 
    for elements in range(1,len(data_orig)): 
     survived=data_orig[elements][1] 
     pclass=data_orig[elements][2] 
     if survived == str(1) and pclass == str(3): 
      count +=1 

    with open(str(target_data_file), 'w') as newfile: 
     data_writer=csv.writer(newfile) 


     if count == 0: 
      return data_orig[0] 
     else: 
      return count 

回答

0

你可以寫入target_data_file與計數循環沿(你不需要data_orig列表)。 那就是:

def third_survived(source_data_file, target_data_file): 
    count= 0 
    with open (str(source_data_file), 'r') as file: 
     data_reader=csv.reader(file) 
     with open(str(target_data_file), 'w') as newfile: 
      data_writer=csv.writer(newfile) 
      for row in data_reader: 
       survived=row [1] 
       pclass=row [2] 
       if survived == "1" and pclass == "3": 
        count +=1 
        data_writer.writerow(row) 

    return count 

如果仍然熱衷於返回的第一行,如果count爲零(頂撞你的文檔) - 你可以添加

first_row = None 

count定義之前權,在每次迭代檢查

if first_row is None: 
    first_row = row 

而最終回報

if count == 0: 
    return first_row 
return count 
0

這對大熊貓來說要容易得多,而且當你使用(kaggle?)數據集時,你會發現很多這方面的幫助。