繁体   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