目录和子目录作为字符串参数传递

时间:2014-05-08 11:24:38

标签: python file recursion directory

问题递归调用目录和子目录并将其作为字符串传递。

在行input_file_list = sys.argv[1:]中我可以将参数作为单个目录传递,但我想传递所有目录和子目录

def main():
    total_lines= comment_lines= blank_lines= code_lines=0
    input_file_list = []


    if len(sys.argv) < 2:
        try:
            inputs_file = open("input.txt", "r")
            for line in inputs_file.readlines():
                if line[-1] == "\n":
                    input_file_list.append(line[:-1])
                else:
                    input_file_list.append(line)
            inputs_file.close()
            if len(input_file_list) == 0:
                print usage
                sys.exit(1)
        except IOError:
            print usage
            sys.exit(1)
    else:
        #Recursively counting the file numbers
        input_file_list = sys.argv[1:]
#        #Recursively counting the file numbers
#        for root, dirs, files in os.walk('./'):
#           for name in files:
#               input_file_name = os.path.join(root, name)
#               #print input_file_name



     #TODO: -Recursively read all the files
    for input_file_name in input_file_list:
        try:
            current_file = open(input_file_name, "r")

任何建议都会非常感激。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试使用此功能:

def get_all_files(parent):
    paths = []
    for root, dirs, files in os.walk(parent):
        for name in files:
            paths.append(os.path.join(root, name))
    return paths