Skip to main content
 首页 » 编程设计

python之编写 Python 函数来遍历行——接受字符串或类似文件的对象

2025年05月04日21freeliver54

我想编写一个 Python 函数来迭代输入参数的行,但可以接受字符串或类似文件的对象。有办法做到这一点吗?

def myfunc(x): 
   for line in x: 
       doSomething(line) 

上面的代码适用于类似文件的对象而不是字符串,我宁愿只写一个函数而不是两个,因为我的实际任务比上面的要复杂得多。

请您参考如下方法:

使用鸭子类型:

def myfunc(x): 
    try: 
        lines = x.split('\n') 
    except AttributeError: 
        lines = x 
    for line in lines: 
        doSomething(line) 

如果需要,您还可以检查类型:

def myfunc(x): 
    if isinstance(x, basestring):  # will work in Python >=2.3, <3.x 
        lines = x.split('\n') 
    else: 
        lines = x 
    for line in lines: 
        doSomething(line)