ManishBharathi
ManishBharathi

Reputation: 37

How to write to a csv file in a next column in python

I currently have a csv file which has four columns

enter image description here

the next time I write to the file, I want to write from E1. I've searched for solutions but none seems to work.

with open(file_location,"w") as csv_file:
            csv_writer = csv.writer(csv_file)
            csv_writer.writerows(list_of_parameters)

where list_of_parameters is a zip of all the four columns.

        list_of_parameters = zip(timestamp_list,request_count_list,error_rate_list,response_time_list)

Anyone have any idea to implement this? Appreciate your help.

Upvotes: 0

Views: 219

Answers (1)

Philip Ciunkiewicz
Philip Ciunkiewicz

Reputation: 2791

The Python library Pandas is very good for these sorts of things. Here is how you could do this in Pandas:

import pandas as pd

# Read file as a DataFrame
df = pd.read_csv(file_location)

# Create a second DataFrame with your new data,
# you want the dict keys to be your column names
new_data = pd.DataFrame({
    'Timestamp': timestamp_list,
    'Key Request': request_count_list,
    'Failure Rate': error_rate_list,
    'Response': response_time_list
})

# Concatenate the existing and new data
# along the column axis (adding to E1)
df = pd.concat([df, new_data], axis=1)

# Save the combined data
df.to_csv(file_location, index=False)

Upvotes: 1

Related Questions