如何将 .txt 文件作为函数参数传递

use*_*455 3 function filepath python-2.7

假设我有一个函数可以读取 .txt 文件并根据该文件中的数据列创建数组。我现在在函数中的内容如下所示:

data = open("some_file_name.txt","r")
Run Code Online (Sandbox Code Playgroud)

但是如果我想更改函数读取的 .txt 文件,我必须手动进入代码并在再次运行之前输入新文件名。相反,我如何将任何文件名传递给函数,使其看起来像:

my_function(/filepath/some_file_name.txt):
    data = open("specified_file_name.txt","r")
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 5

我想你想要

def my_function(filepath):
    data = open(filepath, "r")
    ...
Run Code Online (Sandbox Code Playgroud)

进而

my_function("/filepath/some_file_name.txt")
Run Code Online (Sandbox Code Playgroud)

或更好:

def my_function(data):
    ...
Run Code Online (Sandbox Code Playgroud)

进而

with open("/filepath/some_file_name.txt", "rb") as data:
    my_function(data)
Run Code Online (Sandbox Code Playgroud)

后一个版本允许您将任何类似文件的对象传递给my_function().

更新:如果你想花哨并允许文件名或文件句柄:

def my_func(data):
    if isinstance(data, basestring):
        with open(data, 'rb') as f:
            return my_func(f)
    ...
Run Code Online (Sandbox Code Playgroud)