我正在尝试将日期与日期/时间隔离,这是原始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]
放回原始文件
答案 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)