[英]Writing a python program with output in a spreadsheet
我需要编写一个输出到电子表格的python程序。 在伪代码中,程序将大致如下所示:
folder = 'User/Path/FolderName'
for file in folder:
return filename
functionA(file) #returns OutputA
functionB(file) #returns OutputB
functionC(file) #returns OutputC
这些函数已经用Python编写,所以我宁愿留在Python中。 理想情况下,输出将是如下所示的电子表格(.csv,Excel,制表符分隔的txt等):
FileName A B C
file1 OutputA1 OutputB1 OutputC1
file2 OutputA2 OutputB2 OutputC2
同样理想的是,我将能够在数据文件的另一个文件夹上再次运行该程序,然后将这些结果添加到电子表格中。
我在这里和这里找到了其他问题,以及一些软件包,例如Pyspread ,但我不确定如何解决我的问题。
因此,在查看了csv包之后,我想我会做这样的事情:
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))
为了清楚起见,“ wb”表示我可以写入文件,对吗? 另外,是否需要quotechar =和quoting =语法?
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])
这符合我的预期,即将其放入csv文件中:
1 3 3 -6
2 4 6 -5
3 5 9 -4
4 6 12 -3
但是,如果我使用一组新的数字再次运行它,它将覆盖旧数据。 我想继续向电子表格添加新行。 我该怎么做?
我们用“ ab”代替“ wb”。 'wb'将覆盖文件。
查看http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files了解更多信息
以下内容可能无法解决您眼前的问题,但是有一些Python程序包可以解决读写表的问题: Python Excel
虽然学习曲线可能有点太陡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.