2016-07-20 8 views
0

ディレクトリに複数のファイルの値のCSVを作成するforループがあります。Python:forループで一度だけコマンドを実行する

#name&path to table file 
    test = tablefile+"/"+str(cell[:-10])+"_Table.csv" 

    #write file 
    if not os.path.isfile(test): 
     csv.writer(open(test, "wt"))   
     with open(test, 'w') as output: 
      wr = csv.writer(output, lineterminator=',') 
      for val in header_note: 
       wr.writerow([val]) 

と私が持っているデータを追加する:

作品
 with open(test, 'a') as output: 
     wr = csv.writer(output, lineterminator=',') 
     for val in table_all: 
      wr.writerow([val])  

を私だけのファイルを作成して、一度ヘッダに書き込み、現在私はこれをやっているしたい、このループ内

しかし、もう一度スクリプトを実行すると、同じ.csvファイルの最後にさらに多くのデータが追加されます。私が欲しいのは、forループを使った初めてのことです。既存の.csvを新しいヘッダーで上書きし、その後にデータを追加し続け、スクリプトが再度実行されると上書き/再書き込みを行います。ありがとう!

答えて

0

ファイルの処理以外にいくつかのコードの問題があるようですが、ここでは次のようになります:'w'モードのファイルを開くと、ファイル内のすべてのファイルが上書きされ、'a'モードで開くと、ヘッダー行を変更します。

これを回避するには、ファイルが既に存在する場合は、、次にのファイルを上書きする必要があります。

if os.path.exists(file_name):   # if file already exists 
    with open(file_name, 'r') as in_file: # open it 
    old_lines = in_file.readlines()[1:] # read all lines from file EXCEPT header line 

with open(file_name, 'w') as out_file: # open file again, with 'w' to create/overwrite 
    out_file.write(new_header_line)  # write new header line to file 
    for line in old_lines: 
    out_file.write(line)    # write all preexisting lines back into file 
    # continue writing whatever you want. 

あなたはの線に沿って何かをしたいでしょう

関連する問題