gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:16 24 4
gpt4 key购买 nike

我有以下代码(尝试)清除 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()

最佳答案

我只是读入一个列表,而忽略第二列:

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

的分隔符

关于python - 使用 python 清除或删除 csv 中的第二列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19236567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com