2

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()
2
  • Are you creating a new csv or trying to update an existing one? You can't write a cell of a csv. Its really a bunch of lines with cells separated by commas (or other delimiter). You seem to be using a spreadsheet notation B1 but csv files are not addressable as rows/colums. You can create a list of lists (basically a list of rows) do the update and then save. Commented Feb 23, 2016 at 21:26
  • Thanks for that. I am trying to udate an existing one Commented Feb 27, 2016 at 10:09

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

2 Comments

Why is the comprehension data = [line for line in csv.reader(open('yourfile.csv'))] preferred over something simpler like data = list(csv.reader(open('yourfile.csv'))) since you're pulling out all the data either way?
No reason, just a habit
0

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

1 Comment

This wasn't quite what i was looking for but thanks it does really help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.