截断一个csv文件的列?

时间:2017-02-07 19:45:32

标签: python python-2.7 csv truncate

我是Python的新手,我有以下csv文件(我们称之为out.csv):

DATE,TIME,PRICE1,PRICE2
2017-01-15,05:44:27.363000+00:00,0.9987,1.0113
2017-01-15,13:03:46.660000+00:00,0.9987,1.0113
2017-01-15,21:25:07.320000+00:00,0.9987,1.0113
2017-01-15,21:26:46.164000+00:00,0.9987,1.0113
2017-01-16,12:40:11.593000+00:00,,1.0154
2017-01-16,12:40:11.593000+00:00,1.0004,
2017-01-16,12:43:34.696000+00:00,,1.0095

我想截断第二列,所以csv看起来像:

DATE,TIME,PRICE1,PRICE2
2017-01-15,05:44:27,0.9987,1.0113
2017-01-15,13:03:46,0.9987,1.0113
2017-01-15,21:25:07,0.9987,1.0113
2017-01-15,21:26:46,0.9987,1.0113
2017-01-16,12:40:11,,1.0154
2017-01-16,12:40:11,1.0004,
2017-01-16,12:43:34,,1.0095

这是我到目前为止所拥有的......

with open('out.csv','r+b') as nL, open('outy_3.csv','w+b') as nL3:
  new_csv = []
  reader = csv.reader(nL)
  for row in reader:
      time = row[1].split('.')
      new_row = []
      new_row.append(row[0])
      new_row.append(time[0])
      new_row.append(row[2])
      new_row.append(row[3])
      print new_row
      nL3.writelines(new_row)
  1. 在将每行写入新的csv文件之后,我似乎无法获得新行。
  2. 这绝对看起来或感觉不到pythonic
  3. 由于

1 个答案:

答案 0 :(得分:0)

缺少的换行问题是因为file.writelines()方法没有自动将行分隔符添加到它传递的参数的元素中,它希望它是一个字符串序列。如果这些元素代表单独的行,那么您有责任确保每个元素以换行符结尾。

但是,您的代码尝试使用它只输出一行输出。要解决这个问题,你应该使用file.write(),因为它希望它的参数是一个单独的字符串 - 如果你希望该字符串在文件中是一个单独的行,它必须以换行符结尾或手动添加一个它

下面是执行您想要的代码。它的工作原理是更改csv.reader返回就地的字符串列表中的一个元素,然后将修改后的列表作为 single 将join()字符串全部重新组合在一起,然后手动在结果的末尾添加换行符(存储在new_row中)。

import csv

with open('out.csv','rb') as nL, open('outy_3.csv','wt') as nL3:
    for row in csv.reader(nL):
        time_col = row[1]
        try:
            period_location = time_col.index('.')
            row[1] = time_col[:period_location]  # only keep characters in front of period
        except ValueError:  # no period character found
            pass  # leave row unchanged
        new_row = ','.join(row)
        print(new_row)
        nL3.write(new_row + '\n')

打印(和文件)输出:

DATE,TIME,PRICE1,PRICE2
2017-01-15,05:44:27,0.9987,1.0113
2017-01-15,13:03:46,0.9987,1.0113
2017-01-15,21:25:07,0.9987,1.0113
2017-01-15,21:26:46,0.9987,1.0113
2017-01-16,12:40:11,,1.0154
2017-01-16,12:40:11,1.0004,
2017-01-16,12:43:34,,1.0095