2017-06-18 36 views
0

私はcsvファイルの条件のおかげでデータを選択し、別の方法で編成されたanoter csvファイルに書き込んで、別のデータを選択して同じファイルライン。私はそれを行うためにcsvモジュールと関数のwriterowを使用します。Pythonでcsvファイルを操作する

#Creation of the other csv file 
with open('superAdmins.csv', 'w', newline='') as csvfile: 
    spamwriter = csv.writer(csvfile) 
    spamwriter.writerow(['SuperAdmins'] + ['2 step authentication'] + ['Portée des droits']) 

i = 0 



#Selection of the first data 
with open('admins.csv', 'r') as csvinput,open('2authentication.csv', 'r') as csvinput2, open('superAdmins.csv', 'w+') as csvoutput: 
    reader = csv.DictReader(csvinput, delimiter=',') #lecteur 
    reader2 = csv.DictReader(csvinput2, delimiter=',') #lecteur 

    fieldnames = ['SuperAdmins', '2 step authentication','Portée des droits'] 
    writer = csv.DictWriter(csvoutput,fieldnames = fieldnames) #crayon 

    writer.writeheader() #Ecrit l'en-tête avec les fieldnames 

    for row in reader: 
     # write the selection logic here 
     if row["role"] == "_SEED_ADMIN_ROLE": 
      writer.writerow({'SuperAdmins': row['assignedToUser']}) 


#Selection of the second data 
     for row in reader: 
      print(row["primaryEmail"],superadmin) 
      # write the selection logic here 
      if row["primaryEmail"] == superadmin: 
       if row["isEnforcedIn2Sv"] == "False" and row["isEnrolledIn2Sv"] == "False": 
        writer.writerow({'2 step authentication': "false"}) 

私が手:

SuperAdmins,2 step authentication,Portée des droits 
[email protected],, 
,Test, 
,false, 

私が持っているしたいのに対し:

SuperAdmins,2 step authentication,Portée des droits 
[email protected],Test,false 

私はその関数のwriterowを推測しますそれぞれの用途でコンマを追加して新しい行を始めると、私は同じ行に書き続ける方法を探しています。

ご協力いただきありがとうございます。

答えて

0

'writerow'メソッドは完全な行を書き込みます。したがって、複数のセルが連続している場合は、行全体を1回だけ書き込む必要があります(現在は2回ではありません)。

単純な解決策は、変数(row_dictと呼ばれることもある)を定義し、すべての情報で徐々にそれを埋めることであり、ループの最後に変数を引数としてwriterow関数を使用します。あなたの特定のコードで

for row in reader: 
    row_dict = {} 
    # write the selection logic here 
    if row["role"] == "_SEED_ADMIN_ROLE": 
     row_dict['SuperAdmins'] = row['assignedToUser'] 

     print(row["primaryEmail"],superadmin) 
     # write the selection logic here 
     if row["primaryEmail"] == superadmin: 
      if row["isEnforcedIn2Sv"] == "False" and row["isEnrolledIn2Sv"] == "False": 
       row_dict['2 step authentication'] = ["false"] 

    writer.writerow(row_dict) 
+0

あなたがのOPに関連するいくつかのコードを提供するために喜んでいる場合を除き、これはコメントであるべきでは –

+0

は、あなたの答えをありがとう問います。私はPythonを学び始めていて、「row_dict変数」は一度も使用していません。私はそれについての情報をオンラインで理解していない、それはどのように動作するか尋ねることがありますか? – KB303

+0

@DmitryPolonskiyフェアポイント。 – lesingerouge

関連する問題