【问题标题】:Pythonic way to read 3 csv files in a fucntion?在函数中读取 s3 csv 文件的 Pythonic 方式?
【发布时间】:2017-04-19 13:59:02
【问题描述】:
def production(csvfile):
    # do something with csvfile
    print csvfile

production("somecsvfile.csv")

我想传递 3 个 csv 文件,程序应该给出它的输出。目前我已经给出了一个 csv 文件。

【问题讨论】:

    标签: python csv pandas numpy


    【解决方案1】:

    使用 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)
    

    【讨论】:

      【解决方案2】:

      在函数中添加以下内容

      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)
      

      【讨论】:

      • 您已将 csv 文件作为字符串传递。有没有办法将它们作为单独的文件传递?
      • 这既不是 Python 的方式,也不是好的编程习惯。
      • @Dheeraj 你有两个选项作为生产(['rswm20160901C.csv','rswm20160901C.csv','rswm20160901C.csv'])或通过参数生产(sys.argv)
      【解决方案3】:

      我们不需要使情况过于复杂。 应该这样做:

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

      【讨论】:

      • 仅供参考:我不认为有任何关于它的pythonic。恰到好处的功能使用。
      • 我是编程新手。这就是为什么这对我来说有点复杂。无论如何,谢谢。
      • 没问题。如果您认为它可以解决您的问题,请接受该问题。
      • 我认为这是错误的做法,因为如果需要添加另一个文件功能必须修改。
      • fileList 变量初始化只是示例,它可以从任何源初始化,并且独立于循环。可能是我错过了一些东西。帮助?
      猜你喜欢
      • 2012-05-24
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多