I need to write a python program which outputs to a spreadsheet. In pseudo-code, the program will look roughly like this:
folder = 'User/Path/FolderName'
for file in folder:
return filename
functionA(file) #returns OutputA
functionB(file) #returns OutputB
functionC(file) #returns OutputC
These functions are already written in Python, so I'd prefer to stay in Python. Ideally, the output would be a spreadsheet (.csv, Excel, tab-delimited txt, whatever) that will look something like this:
FileName A B C
file1 OutputA1 OutputB1 OutputC1
file2 OutputA2 OutputB2 OutputC2
Also ideally, I would be able to run the program again on a different folder of files of data, and add those results to the spreadsheet later.
I found these other questions here and here, as well as a few packages such as Pyspread, but I'm not really sure how to go about my problem.
So after looking at the csv package, I think I would do something like this:
import csv
with open('data.csv', 'wb') as data:
datafile = csv.writer(data, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for file in folder:
datafile.writerow(file, functionA(file), functionB(file), functionC(file))
Just to be clear, the "wb" means I can write to the file, correct? Also, are the quotechar= and quoting= required syntax?
import csv
numbers = [1,2,3,4]
def functionA(x):
return x + 2
def functionB(x):
return x * 3
def functionC(x):
return x - 7
with open('data.csv', 'wb') as data:
datafile = csv.writer(data, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for n in numbers:
a = functionA(n)
b = functionB(n)
c = functionC(n)
datafile.writerow([n, a, b, c])
This does what I expected it to, namely put this into the csv file:
1 3 3 -6
2 4 6 -5
3 5 9 -4
4 6 12 -3
However, if I run it again with a new set of numbers, it overwrites the old data. I'd like to keep adding new rows to the spreadsheet. How would I do this?