假设我有一个读取.txt文件并根据该文件中数据列创建数组的函数。我现在在函数中拥有的内容如下:
data = open("some_file_name.txt","r")
但是,如果我想更改函数读取的.txt文件,则必须手动进入代码并键入新文件名,然后再次运行。相反,我如何将任何文件名传递给函数,使其看起来像:
my_function(/filepath/some_file_name.txt):
data = open("specified_file_name.txt","r")
我想你要
def my_function(filepath):
data = open(filepath, "r")
...
进而
my_function("/filepath/some_file_name.txt")
或更好:
def my_function(data):
...
进而
with open("/filepath/some_file_name.txt", "rb") as data:
my_function(data)
后一种版本允许您将任何类似文件的对象传递给my_function()
。
更新:如果您想花哨并允许文件名或文件句柄:
def my_func(data):
if isinstance(data, basestring):
with open(data, 'rb') as f:
return my_func(f)
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句