我必須編寫一個代碼,它需要一個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