1

在清除 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()
4

1 回答 1

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

于 2013-10-07T23:54:05.667 回答