Python:未知的文件#作为函数arg

时间:2015-09-28 01:59:10

标签: python

让这个工作代码读取2个文件并重新打印:

import sys
args = sys.argv[1:]

def funcprint(arg1, arg1):
    with open(arg1, "r") as inp:
        for line in inp:
            print(line)
    with open(arg2, "r") as inp:
        for line in inp:
            print(line)

funcprint("C:/file1.txt", "C:/file2.txt")

但是如何将任意数量的文件传递给函数? *arg代替1& 2会产生TypeError: invalid file:,即使只有1个传递文件。

作为一个附带问题,如果所有文件都在同一个文件夹中,有没有办法缩短函数调用?类似于funcprint("C:/": "file1.txt", "file2.txt")

1 个答案:

答案 0 :(得分:1)

如果您想传递任意数量的文件名,请执行以下操作:

def funcprint(*args):
    for f in args:
        with open(f, 'r') as inp:
            ...

funcprint("C:/file1.txt", "C:/file2.txt")

如果文件都在同一目录中,您可以这样做:

def funcprint(dir, *args):
    for f in args:
        with open('{}{}'.format(dir, f), 'r') as inp:
            ...

funcprint('C:/', 'file1.txt', 'file2.txt')