用python清除或删除csv中的第二列

时间:2013-10-07 23:32:32

标签: python csv

我在清除csv中的第二列数据时有以下代码(尝试):

    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()

我不确定是否或如何清除此列。我应该逐行读取数据并清除每行的第二个条目吗?或者是否有更简单的方法可以一次性清除第二列?

这是第二次尝试:

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()

1 个答案:

答案 0 :(得分:1)

我会在省略第二列时读入列表:

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()。 ..