0

How would I go about writing to a CSV file in Python?

I basically have 2 columns. First column is a list of transaction names, the 2nd column is timings.

I need to create a piece of code that can update the timings column when a user fills in an entry box.

I have setup the entrybox in tkinter and have setup the text variable ready. I'm ok with getting the variable but the problem I am having is taking the textvariable and finding the correct cell in the csv file and overwriting it.

Essentially I want to find the correct cell and paste the value over whats in the csv file.

any ideas?

thanks

1
  • Perhaps check out the module pandas and the functions read_csv and write_csv? Commented Apr 25, 2017 at 23:01

2 Answers 2

2

You can create a temporal file, copy the lines to the tmp file, and then replace only the line that starts with the transaction name. Assuming a CSV with the tuple [name, value] per line, you can use something like this:

from tempfile import mkstemp
from os import close
from shutil import move

def update(filename, name, value):
    fd, path = mkstemp()
    with open(path,'w') as tmpfile:
        with open(filename) as csv:
            for line in cvs:
                if line.startswith(name):
                    tmpfile.write(",".join([name,value]))
                else:
                    tmpfile.write(line)
    close(fd)
    move(path, filename)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice iterative solution, although the OP might want to use the csv module for reading and writing the files since it makes it easy handles the many dialects of the CSV file format that exist in the real world.
1

Assuming you have a file called file.csv that looks like this:

Col1,Col2
entry1,timestamp1
entry2,timestamp2

You can use the csv library like this to modify any entry and paste it in a new .csv.new file (you can choose to remove the '.new' extension but it will overwrite your old file):

import csv
csv_file = "file.csv"

file_dict = {}
with open(csv_file, mode='rb') as f:
    reader = csv.reader(f)
    top_row = next(reader)
    for row in reader:
        file_dict[row[0]] = row[1]

# get transaction name and timing
transaction_name = "entry1"
timing = "timestamp3"

# do the update
file_dict[transaction_name] = timing

# create updated version of file
with open(csv_file+".new", mode='wb') as out_f:
    writer = csv.writer(out_f)
    writer.writerow(top_row)
    writer.writerows(file_dict.items())

Note this will likely rearrange your csv file. You didn't specify if this was a concern or not. If it is you can sort the dict or use an OrderedDict. See here for more info: https://docs.python.org/2/library/collections.html#collections.OrderedDict

3 Comments

This requires reading the entire file into memory, which might be an issue (and is unnecessary in any case).
I am getting a syntax error on the above solution at the very first file_dict = {}. Is this because its the third part of a function? it starts as def updatetimings(): ask = messagebox.askquestion('Validation','Are you sure you want to update timings?') if ask =='yes': try: newv5ctiming = float(newv5c.get()) newv62timing = float(newv62.get()) newdisptiming = float(newdisp.get()) csv_file = "Timings.csv" timings_list =[] The first few steps work fine but a syntax appears when it hits file_dict = {}
What's the error you're getting? You might need to look it up or post another overflow question IF it's not already on here.

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.