简体   繁体   中英

Python - How to write data out to a new csv file

Ok, so I'm fairly new to Python and I have a .csv file which contains data for racers names, start and finish times. I need to calculate the time taken and output the additional information, plus the earlier data to a new .csv.

This is what I have so far:

import csv
input_file = csv.DictReader(open("runners_times.csv"))
for row in input_file:
    time_taken = float(row["finish_time"])-float(row["start_time"])
    print (row)
    print (time_taken)

with open("runners_times_appended.csv", "w+") as to_file:
        writer = csv.writer(to_file, delimiter=",")
        for row in input_file:
            writer.writerows(all)

This is creating the new .csv but the file is empty. Your Help is gratefully appreciated.

I didn't fully understand how are you using time_taken in your file which you are going to save.
As I understand you need to add/change column in your dataFrame/csvFile with time_taken. You could do it with pandas package:

import pandas as pd
df = pd.read_csv("runners_times.csv")
df["time_taken"] = df["finish_time"] - df["start_time"]
df.to_csv("new_name.csv")

Try this:

import csv
data_list = []
input_file = csv.DictReader(open("runners_times.csv"))
for row in input_file:
    time_taken = float(row["finish_time"])-float(row["start_time"])
    row.update({"time_taken":time_taken})
    data_list.append(row)
keys = data_list[0].keys()
with open("runners_times_appended.csv", "w") as fp:
    dict_writer = csv.DictWriter(fp, keys)
    dict_writer.writeheader()
    dict_writer.writerows(data_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM