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

2024-04-26 14:04:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我将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文件的第n行?在

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

^{pr2}$

我尝试过:

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]

Tags: 文件csvintxtforsqliteopenreader
1条回答
网友
1楼 · 发布于 2024-04-26 14:04:50

要检索第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)

相关问题 更多 >