【问题标题】:How can I pass a excel/csv file as a function parameter?如何将 excel/csv 文件作为函数参数传递?
【发布时间】:2021-03-14 10:34:03
【问题描述】:

如何将 excel/csv 文件作为函数参数传递? 我写了一段代码来将内容从一个 excel 文件复制到另一个 excel 文件。现在我想将它定义为一个函数,所以我只需要提及我想要将数据传输到现有文件的文件名。 提前非常感谢。 我是 Python 编程的新手,期待学到很多东西。

def feed_input_file(InputFile):

   InputFile = "D:\\Python_Projects\\ABC.xlsx"  #(I am passing Input file at the moment but I don't wanna pass it here)

#(这里我尝试调用我的函数参数值)

Workbook1 = xl.load_workbook(feed_input_file(InputFile))

............

【问题讨论】:

  • 你想定义什么作为函数?抄袭还是抄写?请表现出一些努力
  • 嗨 itprorh66,当然,我定义我的函数有点像:############## def feed_input_file(InputFile): InputFile = "D:\\Python_Projects\ \ABC.xlsx" #( 这里我试图调用我的函数参数值) Workbook1 = xl.load_workbook(feed_input_file(InputFile)) ################# 问题是在第二行我不知道如何使我的论点任意而不是硬编码输入文件 ABC.xlsx 你有什么建议吗?
  • 您可以编辑您的问题以使用代码标记显示代码吗?按照目前的写法无法理解。

标签: python-3.x excel function file-io parameter-passing


【解决方案1】:

仍然不太确定您要做什么,但如果您想创建一个将文件名作为参数的函数,您可以尝试以下方式:

def processFile(fn:str):
    #Reads in the contents of file specified by fn
    content = ''
    with open(fn, 'a') as f:
        data = f.read()
        #Do something with data here to create content
    return content

然后在脚本的主要部分

for filename in listofFiles:
    fle_out = processFile(filename
    #Do something here with file contents

【讨论】:

  • 非常感谢 itprorh66。它对我有用。
  • 如果这解决了您的问题,请将问题标记为已回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
  • 2017-10-09
  • 2021-01-14
  • 1970-01-01
相关资源
最近更新 更多