簡體   English   中英

用電子表格中的輸出編寫Python程序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM