Reputation: 31
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
Upvotes: 0
Views: 1008
Reputation: 491
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
Upvotes: 1
Reputation: 415
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)
Upvotes: 2