首页 > 解决方案 > Python只打印一个文件

问题描述

有人可以解释一下,为什么我的函数 out() 只打印一个文件?我该如何解决,bcs它应该从2019 DIR递归打印很多文件

class log():

    def __init__(self, search):
        self.search = search

    def get_files(self):
        path = '/var/log/HOSTS/dhcpd-s/2019'
        for root, directories, filenames in os.walk(path):
            for directory in directories:
                #do whatever u want with absolute dirs path
                dir_path = os.path.join(root, directory)

            for filename in filenames:
                #do whatever u want with absolute file path
                file_path = os.path.join(root, filename)
                if os.path.getsize(file_path) == 0:
                    pass
                else:
                    self.file_path = file_path

    def out(self):
        print(self.file_path)


if __name__=='__main__':
   p = log(search = sys.argv[1])
   p.get_files()
   p.out()

标签: pythonfunctionclass

解决方案


您正在循环运行

self.file_path = file_path

在每次迭代中,它分配新的文件路径,并在退出循环后保存上次迭代的值。

您可以声明self.file_pathlist

def __init__(self, search):
        self.search = search
        self.file_path = []

并追加file_path到列表中

self.file_path.append(file_path)

现在您可以打印所有路径

def out(self):
    for path  in self.file_path:
        print(path)

推荐阅读