1

csv の 2 列目のデータをクリアする次のコード (試行) があります。

    def del_col(in_path):
    # read file into memory
        file_obj = open(in_path, 'rb')
        reader = csv.reader(file_obj, delimiter='\t')


# delete the status column here:



# Now write csv back to same file: 

        # write data to file
        file_obj = open(in_path, 'rb')
        writer = csv.writer(file_obj)
        writer.writerows(data)
        file_obj.close()

この列をクリアするかどうか、またはクリアする方法がわかりません。データを行ごとに読み込んで、各行の 2 番目のエントリをクリアする必要がありますか? または、2 番目の列を一度にクリアする単純な方法はありますか?

2回目の試みは次のとおりです。

def del_col(in_path):
    # read file into memory
    file_obj = open(in_path, 'rb')
    reader = csv.reader(file_obj, delimiter='\t')
    data = []
    for row in reader:

    # delete the status column here:

        vals = [x[:1] + x[2:] for x in reader]
        print vals
        file_obj.close()

    print 'Delete the 2nd Column (Lead Status?)'
    conf = raw_input('delete these leads? (Y|N): ').upper()[0]

    if conf == 'Y':
        # write data to file
        file_obj = open(in_path, 'wb')
        writer = csv.writer(file_obj)
        writer.writerows(data)
        file_obj.close()
4

1 に答える 1

1

2 番目の列を省略してリストを読み込むだけです。

def del_col(in_path):
    # read file into memory
    file_obj = open(in_path, 'rb')
    readfile = csv.reader(file_obj, delimiter='\t')

    # delete the status column here:

    vals = [row[:1] + row[2:] for row in readfile]
    print vals
    file_obj.close()  # if you are going to use the same file name, close and re-open

    # Now write csv to new file: 
    # write data to file
    out_path = in_path + "_out.dat"
    out_obj = open(out_path, 'w')
    writefile = csv.writer(out_obj, delimiter='\t')
    writefile.writerows(vals)
    out_obj.close()

その他の考慮事項: 読み取り元と同じファイルに書き込まないでください。(この場合、古い名前に基づいて新しい名前を生成しました。)目的のファイルを'w'代わりに開く必要が'r'あり、区切り文字をcsv.writer()...に追加する必要がありました。

于 2013-10-07T23:54:05.667 に答える