Ardrito
Ardrito

Reputation: 19

How to write to a specific cell in a csv file from Python

I am quite new to python and am trying to write to a specific cell in a csv file but I can't quite figure it out.

This is part of it, but I don't know how to get it to write the score (line 3) to the cell I want. e.g cell "B1":

file = open(class_name + ".csv" , 'a')
file.write(str(name + " : " ))
file.write(str(score))
file.write('\n')
file.close()

Upvotes: 2

Views: 7503

Answers (3)

Marcelo Assis
Marcelo Assis

Reputation: 5194

You just have to separate your columns with commas and your lines with linebreaks. There's no mystery:

name1 = "John"
name2 = "Bruce"
job1 = "actor"
job2 = "rockstar"

csv_str = ""
csv_str += name1 +";"+job1+"\n"  #line 1
csv_str += name2 +";"+job2+"\n"  #line 2

file = open(class_name + ".csv" , 'a')
file.write(csv_str)
file.close()

This will generate a 2x2 grid

Upvotes: 0

Nick Burns
Nick Burns

Reputation: 192

Pandas will do what you're looking for

import pandas as pd

# Read csv into dataframe
df = pd.read_csv('input.csv')
# edit cell based on 0 based index b1=1,0
df.ix(1,0) = score
# write output
df.to_csv('output.csv', index=False)

Upvotes: 2

Mad Wombat
Mad Wombat

Reputation: 15105

There is a CSV reader/writer in python that you can use. CSV files don't really have cells, so I will assume that when you say "B1" you mean "first value in second line". Mind you, that files do not behave the way a spreadsheet behaves. In particular, if you just start writing in the middle of the file, you will write over the content at the point where you are writing. Most of the time, you want to read the entire file, make the changes you want and write it back.

import csv

# read in the data from file
data = [line for line in csv.reader(open('yourfile.csv'))]
# manipulate first field in second line
data[1][0] = 'whatever new value you want to put here'
# write the file back
csv.writer(open('yourfile.csv', 'w')).writerows(data)

Upvotes: 0

Related Questions