簡體   English   中英

用Pythonic的方法可以讀取3個csv文件?

[英]Pythonic way to read 3 csv files in a fucntion?

def production(csvfile):
    # do something with csvfile
    print csvfile

production("somecsvfile.csv")

我想傳遞3個CSV文件文件,程序應為其輸出。當前我給出了一個CSV文件。

在函數中添加以下內容

fileList = csvfiles.split(",")
for files in filesList:
    data = read_csv(csvfile)
    ....
    ....


production("rswm20160901C.csv,rswm20160901E.csv,rswm20160901D.csv")

要么

import sys
def production(csvfile)
......
......

fileList = sys.argv[1:] # pass the functions in command line
for f in fileList:
    production(f)

我們不需要使情況復雜化。 應該這樣做:

def production(csvfile)
......
......

fileList = ['a.csv','b.csv','c.csv']
for f in fileList:
    production(f)

使用可以接受任意數量參數的python *args參數解包。 它適用於任何數量的參數

def production(*csvfile):
    for csv in csvfile:
        # do something with csvfile
        print(csv)

production("file1.csv", "file2.csv", "file3.csv")
# code above will printout 
# file1.csv 
# file2.csv 
# file3.csv
production("file1.csv")
# just print out 
# file1.csv

如果您希望它是精確的3個輸入文件,則可以定義3個輸入(如下面)或1個列表輸入,它們也適用於任何列表長度

def production(csvfile1, csvfile2, csvfile3):
    for csv in [csvfile1, csvfile2, csvfile3]:
        # do something with csvfile
        print(csv)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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