如何使用python删除csv文件的每第n行的特定列

时间:2012-08-20 15:08:32

标签: python csv

我将sqlite 3查询的结果写入csv文件,如:

2221,5560081.75998,7487177.66,237.227573347,0.0,5.0,0.0
2069,5559223.00998,7486978.53,237.245992308,0.0,5.0,0.0
10001,5560080.63053,7487182.53076,237.227573347,0.0,5.0,0.0
1,50.1697105444,20.8112828879,214.965341376,5.0,-5.0,0.0
2,50.1697072935,20.8113209177,214.936598128,5.0,-5.0,0.0
10002,50.1697459029,20.8113995467,214.936598128,5.0,-5.0,0.0
1,50.1697105444,20.8112828879,214.965341376,-5.0,-5.0,0.0
2,50.1697072935,20.8113209177,214.936598128,-5.0,-5.0,0.0
10003,50.1697577958,20.8112608051,214.936598128,-5.0,-5.0,0.0

我的第一个常见问题是如何用python选择每一行csv或txt文件?

我的具体问题是如何删除每两行csv文件的最后三列,让每三行都没有变化? outpu就像:

2221,5560081.75998,7487177.66,237.227573347
2069,5559223.00998,7486978.53,237.245992308
10001,5560080.63053,7487182.53076,237.227573347,0.0,5.0,0.0
1,50.1697105444,20.8112828879,214.965341376
2,50.1697072935,20.8113209177,214.936598128
10002,50.1697459029,20.8113995467,214.936598128,5.0,-5.0,0.0
1,50.1697105444,20.8112828879,214.965341376
2,50.1697072935,20.8113209177,214.936598128
10003,50.1697577958,20.8112608051,214.936598128,-5.0,-5.0,0.0

我特别尝试过:

fi = open('file.csv','r')
for i, row in enumerate(csv.reader(fi, delimiter=',', skipinitialspace=True)):
    if i % 3 == 2:
        print row[0:]
    else:
        print row[0], row[1], row[2], row[3]

1 个答案:

答案 0 :(得分:1)

要检索第n行,最容易迭代,但您可以使用line cache module来抓取它。

要回答其他部分,假设您想要一个具有所需品质的新csv文件:

my_file = []
with open('file.csv','r') as fi:
    for i, row in enumerate(csv.reader(fi, delimiter=',', skipinitialspace=True)):
         if i % 3 == 2:
             my_file.append(row)
         else:
             my_file.append(row[:-3])

#if you want to save a new csv file
with open('new_file.csv', 'wb') as new_fi:
    new_fi_writer = csv.writer(new_fi, delimiter=', ')
    for line in my_file:
        new_fi_writer.writerow(line)

#alternatively (if you just want to print the lines)
for line in my_file:
    print ' '.join(line)