【问题标题】:How to remove specific columns of every nth line of csv file using python如何使用python删除每n行csv文件的特定列
【发布时间】:2012-08-20 15:08:32
【问题描述】:

我将 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]

【问题讨论】:

  • 查看csv module,了解快速读取/输出 csv 数据的方法。
  • 既然您是从 SQLite 中提取数据,那么在此处获取有趣的数据不是更有意义吗?
  • 好主意,但我的sqlite技术不够熟练:(
  • 如果你希望写入到csv文件(即改变它),你需要读写,使用'r+'而不是'r'(见@ 987654322@) 或者,请参阅this answer

标签: python csv


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多