0

我将 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 选择每第 n 行 csv 或 txt 文件?

而我的具体问题是如何删除每两行 csv 文件的最后三列,而每三行保持不变?输出将是:

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]
4

1 回答 1

1

要检索第 n 行,最容易迭代,但您可以使用行缓存模块来获取它。

要回答另一部分,假设您想要一个具有所需质量的新 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)
于 2012-08-20T16:19:36.010 回答