你会如何放回一个你已经拆分并转换回原始文件的列表?

时间:2016-07-04 15:08:25

标签: python python-2.7 csv

我正在尝试将日期与日期/时间隔离,这是原始csv文件中的一列。我已经隔离了该列并将其更改为刚才的日期,但我很难将其恢复到原始文件中:

def isolateDate(csv_file):
    file_in = open(csv_file, "rU")
    reader = csv.reader(file_in)
    next(file_in,None)
    for line in reader:
        date = line[3]
        date = date.split()
        new_date = date[0]
    return new_date

如何将new_date变量作为line[3]放回原始文件

1 个答案:

答案 0 :(得分:1)

您需要读入文件中的所有行,修改第4列(索引3),然后重写回文件:

with open(csv_file, "r") as file_in:
    reader = csv.reader(file_in)
    header = next(reader)
    rows = [row[0:3] + [row[3].split()[0]] + row[4:]  for row in reader]
    #                  ^^^modified date^^^

with open(csv_file, "w") as file_in:
    writer = csv.writer(file_in)
    writer.writerow(header)
    writer.writerows(rows)