我在我的CSV清除數據的第2列下面的代碼(未遂):清除或CSV文件中刪除第2列與Python
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次嘗試:
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()
請使用下面的代碼,而不是額外的'在閱讀器循環中行。 'vals ='行是'for'循環的單行版本,它貫穿讀者的每一行,所以'for row'行會混淆視聽。我編輯我的答案,使用名稱'行'而不是'x'來避免混淆... – beroe