我想编写一个python程序来处理csv表,每次行和列的总数不同。
我想要做的一件事就是删除包含特定字符串的列。
import csv
input = open("1.csv","rb")
reader = csv.reader(input)
output = open("2.csv","wb")
writer = csv.writer(output)
index = -1
for row in reader:
for item in row:
if item == str('string'):
index = row.index(item)
print(index)
...
更新:由于tuan-huynh,我重写了代码,但此代码仅适用于包含"字符串"的第一列。
答案 0 :(得分:0)
您可以使用此代码找到列索引,并可以将其删除。我测试好了
导入csv
with open("SampleCSVFile_2kb.csv","rb") as source:
rdr= csv.reader( source )
with open("result","wb") as result:
wtr= csv.writer( result )
index = -1
for r in rdr:
for item in r:
if item == str(string):
index = r.index(item)
答案 1 :(得分:-1)
假设csv看起来像
name,color,price
apple,red,10
banana,yellow,5
import csv
with open(file_path, "r") as f:
file = csv.reader(f)
for line in file:
print(line[0], line[1], line[2])
打印出来
name color price
apple red 10
banana yellow 5