0

How the csv looks like

col1,col2,col3,col4,col5
value1,value2,value3,value4,value5
,,value6,value7,value8,value9
,,value10,value11,value12,value13

how my function looks so far

def append(file, value1, value2):
    with open(file, 'a',) as file:
        writer = csv.writer(file, quoting=csv.QUOTE_NONE, escapechar=' ')
        writer.writerow([value1, value2])

The append function is called inside a function where value 1 and value 2 are passed from.

If the csv file looks like the below, the function does the job

col1,col2,col3,col4,col5
value1,value2,value3,value4,value5

How could I write to a particular cell for as long as value1 and value2 are passed in. Don't need to wory about the values being passed, just for the function to introduce the arguments.

the csv would look like:


col1,col2,col3,col4,col5
value1,value2,value3,value4,value5
,,value6,value7,value8,value9
,,value10,value11,value12,value13

Expected result


col1,col2,col3,col4,col5
value1,value2,value3,value4,value5
argument1,argumen2,value6,value7,value8,value9
argument3,argument3,value10,value11,value12,value13

7
  • 1
    Use \n at begining of the line, and in the final. The idea is know if your files always comes without the return of line. Commented May 9, 2021 at 22:51
  • Thanks. I've updated the post, do you have a suggestion for the quotes? Commented May 9, 2021 at 23:17
  • Why are you using newline='' in the open command? Commented May 9, 2021 at 23:24
  • I forgot about it. When i started thinking about this I was convinced that i will write to it, but then i realised I need to append because writing will overwrite the file. Commented May 9, 2021 at 23:30
  • Read the two articles I think you can understand. thispointer.com/how-to-append-text-or-lines-to-a-file-in-python Commented May 10, 2021 at 21:10

1 Answer 1

1

That way is how I was learned and is so easy:

def append_csv(file, *argv):
    my_line = ','.join([elem for elem in argv]) + '\n'
    file.write(my_line)
  
my_file = open('my_csv_file.csv', 'a')
append_csv(my_file, 'val1', 'val2', ... , 'valN')
my_file.close() # you need to close to save the changes.
Sign up to request clarification or add additional context in comments.

9 Comments

I will give your code a try tmrw, but what i have it's pretty readable. your's is fancy.
don't know what type of code is that. is it python3.8 ?
When I put out of loop is a comment. Is Python3 yes. It is easier work with file.write instead of writer
I just updated the post, I found a bug that i did not consider, if you have the time to take a look.
It has a little job. Actually I will sleep, tomorrow I give you the answer. You can pass into function *args, and you don’t have to care about number of arguments
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.