这样做的一种方式,没有安装像numpy/pandas这样的第三方模块,如下所示。给定一个输入文件,名为 “input.csv” 是这样的:
A,B,c_net,d,e_net
0,0,1,0,1
0,0,1, 0,1
(去除之间的空行,它们只是格式化这个职位的 内容)
下面的代码你想要做什么。
import csv
input_filename = 'input.csv'
output_filename = 'output.csv'
# Instantiate a CSV reader, check if you have the appropriate delimiter
reader = csv.reader(open(input_filename), delimiter=',')
# Get the first row (assuming this row contains the header)
input_header = reader.next()
# Filter out the columns that you want to keep by storing the column
# index
columns_to_keep = []
for i, name in enumerate(input_header):
if 'net' in name:
columns_to_keep.append(i)
# Create a CSV writer to store the columns you want to keep
writer = csv.writer(open(output_filename, 'w'), delimiter=',')
# Construct the header of the output file
output_header = []
for column_index in columns_to_keep:
output_header.append(input_header[column_index])
# Write the header to the output file
writer.writerow(output_header)
# Iterate of the remainder of the input file, construct a row
# with columns you want to keep and write this row to the output file
for row in reader:
new_row = []
for column_index in columns_to_keep:
new_row.append(row[column_index])
writer.writerow(new_row)
请注意,没有错误处理。至少应该处理两个。第一个是检查输入文件是否存在(提示:检查os和os.path模块提供的功能)。第二个是处理空白行或列数不一致的行。
你能请附上您的文件的一个小样本有问题,使问题陈述更清楚一点? – ZdaR
当然!我已经获得了帮助,但是我现在包含了一段代码样本的小图片,以防将来帮助任何人 – Rickyboy