【问题标题】:directory and sub directory pass as a string argument目录和子目录作为字符串参数传递
【发布时间】:2014-06-25 18:20:22
【问题描述】:

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

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")

任何建议将不胜感激。谢谢。

【问题讨论】:

  • os.walk() 不行?
  • 您在注释的代码中没有解决您的问题的方法吗?
  • @fred.yu os.walk works 列出了所有目录和子目录。问题出在传递 input_file_list 值的注释行中。我需要在下一个 for 循环中传递这个 input_file_list。
  • @HansThen 我仍在处理这个已评论的待办事项列表。

标签: python file recursion directory


【解决方案1】:

尝试使用这个功能:

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

【讨论】:

    猜你喜欢
    • 2013-05-07
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    相关资源
    最近更新 更多