文件结构大致如下:
-- kafka
|__ __init__.py
|__ .idea/
|__ docstest/
| |__ asdfk.py
| |__ kafkaProducer.py
| |__ kazooo.py
| |__ zooka.py
|__ test/
|__ kafkaComsuer.py
|__ kafkaProducer.py
我们要做的是在asdfk.py文件中编写读取kafka文件夹下的所有文件内容,代码如下:
#! -*-coding: utf-8 -*-
import os
path = "../" # 文件夹目录
def read_file(file_name): # 读取文件内容并返回
f = open(file_name)
iter_f = iter(f)
str = ""
for line in iter_f: # 遍历文件,一行行遍历,读取文本
str = str + line
return str
def write_file(paths):
flag = True # 定义一个判断标示
data = [paths] # 置一个存放文件夹的list, 这里将要读取的文件夹存入
while flag:
for i in xrange(len(data)): # 遍历目录list
file_path = data.pop() # 取出一个文件目录
files = os.listdir(file_path) # 读出目录中的下一级所有文件名和文件夹
for file in files: # 遍历文件夹
print file_path+file
if not os.path.isdir(file_path+file): # 判断是否是文件夹,不是文件夹才打开
str = read_file(file_path+file)
# print str
else:
if "." not in file: # 筛选文件夹,去掉隐藏文件
data.append(file_path + file + "/") # 加入文件夹list
if len(data) <= 0: # 判断文件夹数量,如果为0则置换标示,终止循环
flag = False
write_file(path)
这里只打印了目录, 没有打印文件内容(因为太多了),打印结果如下:
E:\usr\Anaconda2\python.exe D:/workspace/kafka/docstest/asdfk.py
../
../.idea
../docstest
../test
../__init__.py
../test/
../test/kafkaComsuer.py
../test/kafkaProducer.py
../docstest/
../docstest/asdfk.py
../docstest/kafkaProducer.py
../docstest/kazooo.py
../docstest/zooka.py
Process finished with exit code 0