python - 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()
解决方案
您正在循环运行
self.file_path = file_path
在每次迭代中,它分配新的文件路径,并在退出循环后保存上次迭代的值。
您可以声明self.file_path
为list
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)
推荐阅读
- sql - 本机查询在 MS SQL Server Management Studio 上工作,但不在代码上
- if-statement - 比较可能有也可能没有界限的 2 个范围
- java - 将值放入 java8 映射时,是否有类似 getOrDefault 的东西?
- node.js - CodeceptJS:分配标签的语义检查
- key-bindings - 在 tmux 中构建自动化配置
- python - 从选择列表中获取对象的 ID。Django,表格
- android - 使用 XmlPullParser 为特定标签解析 XML?
- azure-application-insights - Kusto 查询渲染函数忽略指定的 Y 范围
- java - 聚合多个休息调用spring boot 2
- javascript - 内容编辑模式应该是 ContentCard 组件的一部分吗?