python的 for dirpath, dirnames, filenames in os.walk(rs_path):

假设这三个目录三个文件放在 rs_path=d:/gmz 目录里面。那么要获取所有的文件路径,可以用如下方式

for parentpath, dirnames, filenames in os.walk(rs_path):

  for filename in filenames:
  print "filePath:" + parentpath +
"/" + filename

//这里总共会遍历四次,parentpath包含了所有文件父目录的可能即:

d:/gmz/Battlefield

d:/gmz/card

d:/gmz/font

d:/gmz

 

2 多行注释可以 定义一个不用的变量 _ggmz=‘‘‘  这里放置需要注释的内容 ‘‘‘ (重点是三个引号标识注释)

//基本使用

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

import
os,sys

from xml.etree import
ElementTree as ET

import
json

# resources path

rs_path =
"Resources"

# classes path

cs_path =
"Classes"

# resource define

h_file =
cs_path +
"/Resources.h"

js_file =
rs_path +
"/file_list.json"

# json define

file_name_key =
"file_name"

file_index_key =
"file_index"

texture_name_key =
"texture_name"

texture_plist_key =
"texture_plist"

texture_image_key =
"texture_image"

dir_list =
[]

file_list =
[]

texture_list =
[]

# 初始化方法

def
init():

    # 填充所有目录和文件名称

    for
dirpath, dirnames, filenames in
os.walk(rs_path):

        #----wxw add start----

        #不对ui目录进行编码,避免与UI数据冲突

        #str = dirpath[-2] + dirpath[-1]

        if
dirpath.find("\ui") !=
-1:

            continue

        #----wxw add end----

        

        dir_list.append(dirpath)

        for
filename in
filenames:

            print
"filePath:" +
dirpath +
"/" + filename

            file_list.append(dirpath +
"/" + filename)

    # 填充 texture

    for
filename in
file_list:

        name, ext =
os.path.splitext(filename)

        if
ext ==
".plist":

            texture_list.append(filename)

    

# 根据扩展名称返回缩写

def
getPreByExt(ext):

    if
ext.find(‘.‘) >=
0:

        ext =
ext[1:]

    ext_dict =
{

        "png": "i",

        "jpg": "i",

        "plist": "p",

        "ttf": "t",

        "gif": "i",

        "db": "d",

        "json": "js"

    }

    if
len(ext) > 0:

        return
ext_dict[ext]

    else:

        return
""

def
generate_h():

    if
os.path.isfile(h_file):

        os.remove(h_file)

    f =
file(h_file, ‘w‘)

    f.write("#ifndef _AUTO_RESOURCES_H_\n")

    f.write("#define _AUTO_RESOURCES_H_\n\n")

    # 生成目录定义

    f.write("// search paths\n")

    # ----wxw add start----

    f.write("static const std::string array[] = {\n")

    # ----wxw add end----

    #f.write("static const std::vector<std::string> searchPaths = {\n")

    for
dirname in
dir_list:

        name =
dirname[len(rs_path) +
1:]

        if
len(name) > 0:

            f.write(‘\t"%s",\n‘
% name )

    f.write("};\n")

    # ----wxw add start----

    f.write("static const std::vector<std::string> searchPaths(array,array + array->size());\n\n")

    # ----wxw add end----

    res_format =
‘static const char s%s_%s[]\t\t = "%s"; \n‘

    # 生成资源定义

    f.write("// files\n")

    for
filename in
file_list:

        # 去路径

        filename =
os.path.basename(filename)

        name, ext =
os.path.splitext(filename)

        # 去空格

        name =
name.replace(‘ ‘, ‘‘)

        # 前缀

        ext_pre =
getPreByExt(ext)

        f.write(res_format %
(ext_pre, name, filename))

    # 生成打包资源定义

    f.write("\n\n////// texture //////\n")

    for
filename in
texture_list:

        name, ext =
os.path.splitext(filename)

        root =
ET.parse(filename).getroot()

        # ----wxw add start----

        #修改原有代码,兼容TexturePackerGUI生成的plist文件

        dictLen =
len(root[0])

        for
i in
range(0,dictLen):

            if
root[0][i].text ==
"frames":

                f.write("\n// %s\n"
% os.path.basename(filename))

                for
elem in
root[0][i +
1]:

                    if
elem.tag ==
"key":

                        image =
elem.text

                        name, ext =
os.path.splitext(image)

                        # 去空格

                        name =
name.replace(‘ ‘, ‘‘)

                        # 前缀

                        ext_pre =
getPreByExt(ext)

                        f.write(res_format %
(ext_pre, name, image))

        # ----wxw add end----

        """

        if root[0][0].text == "texture":

            f.write("\n// %s\n" % os.path.basename(filename))

            # images = root[0][3].find("key")

            for elem in root[0][3]:

                if elem.tag == "key":

                    image = elem.text

                    name, ext = os.path.splitext(image)

                    # 去空格

                    name = name.replace(‘ ‘, ‘‘)

                    # 前缀

                    ext_pre = getPreByExt(ext)

                    f.write(res_format % (ext_pre, name, image))

        """

    # 生成 json key 定义

    f.write("\n// json key\n")   

    write_key_define =
lambda key: f.write(‘static const char %s[]\t\t = "%s"; \n‘
%  (key, key))

    write_key_define(file_name_key)

    write_key_define(file_index_key)

    write_key_define(texture_name_key)

    write_key_define(texture_plist_key)

    write_key_define(texture_image_key)

                    

    

    f.write("\n#endif // _AUTO_RESOURCES_H_\n")

# 生成配置文件,字典

def
generate_json():

    file_name =
[]

    file_index =
[]

    texture_name =
[]

    texture_plist =
[]

    texture_image =
[]

    for
idx, filename in
enumerate(file_list):

        file_index.append(str(idx +
1))

        file_name.append(os.path.basename(filename))

        name, ext =
os.path.splitext(filename)

        if
ext ==
".plist":

            root =
ET.parse(filename).getroot()

            # ----wxw add start----

            #修改原有代码,兼容TexturePackerGUI生成的plist文件

            dictLen =
len(root[0])

            for
i in
range(0,dictLen):

                if
root[0][i].text ==
"frames":

                    for
elem in
root[0][i+1]:

                        if
elem.tag ==
"key":

                            image =
elem.text

                            texture_plist.append(str(idx +
1))

                            texture_name.append(image)

                            texture_image.append(str(idx +
2))

            # ----wxw add end----

            """

            if root[0][0].text == "texture":               

                for elem in root[0][3]:

                    if elem.tag == "key":

                        image = elem.text

                        texture_plist.append(str(idx + 1))

                        texture_name.append(image)

                        texture_image.append(str(idx + 2))

            """

    json_file =
{

        file_name_key: file_name,

        file_index_key: file_index,

        texture_name_key: texture_name,       

        texture_plist_key: texture_plist,

        texture_image_key: texture_image

    }

    

    if
os.path.isfile(js_file):

        os.remove(js_file)

    f =
file(js_file, ‘w‘)

    f.write(json.dumps(json_file, indent =
2))

    f.close()

init()   

generate_h()

generate_json()

print("leaf ~")

  

python的 for dirpath, dirnames, filenames in
os.walk(rs_path):

时间: 2024-08-06 21:58:19

python的 for dirpath, dirnames, filenames in os.walk(rs_path):的相关文章

python遍历文件夹中所有文件夹和文件,os.walk

python中可以用os.walk来遍历某个文件夹中所有文件夹和文件. 例1: import os filePath = 'C:/Users/admin/Desktop/img' for dirpath, dirnames, filenames in os.walk(filePath): print(dirpath, dirnames, filenames) 输出结果: 例2: import os filePath = 'C:\\Users\\admin\\Desktop\\img' for d

python【使用简单的os.walk生成目录树】

思路比较简单,使用os.walk 生成目录信息,然后再进行字符串操作,所以没有其他比较复杂的逻辑,但是生成的效果也比较简单,自己看看到是可以哈. 代码如下 # -*- coding: utf-8 -*- ''' Created on July 22, 2017 @author: hehe1234567 ''' import os def simple_dir_tree(ddir): for dirpath,dirnames,filenames in os.walk(ddir.strip(os.s

Python文件与文件系统(2)——os模块对文件、文件系统操作的支持

三.文件系统操作 os模块的功能主要包括文件系统部分和进程部分,这里介绍其中与文件系统相关的部分. 当请求操作系统失败时,os模块返回内置异常 exceptions.OSError 的实例,可以通过 os.error 访问这个类型,OSError的实例有三种属性: errno:操作系统错误的错误代码 strerror:描述错误的字符串: filename:操作在哪个文件上出错. os模块提供的有用属性 >>> os.curdir'.' 表示当前目录的字符串,Unix和Windows上都是

python使用os.listdir和os.walk获得文件的路径

目录 情况1:在一个目录下面只有文件,没有文件夹,这个时候可以使用os.listdir 情况2:递归的情况,一个目录下面既有目录也有文件,使用os.walk: os.walk介绍: 如何获得一个路径下面所有的文件路径: 正文 回到顶部 情况1:在一个目录下面只有文件,没有文件夹,这个时候可以使用os.listdir 在我们的桌面上有一个file目录(文件夹),里面有三个文件 file(dir)| --|test1.txt --|test2.txt --|test3.txt 用下面的程序获得文件的

Python3.x:os.listdir和os.walk(获取路径方法)的区别

Python3.x:os.listdir和os.walk(获取路径方法)的区别 1,os.listdir 使用情况:在一个目录下面只有文件,没有文件夹,这个时候可以使用os.listdir: 例如:d:\listdir文件夹下有三个文件(text1.txt.test2.txt.test3.txt),获得文件的绝对路径: import os path = r'd:\listdir' for filename in os.listdir(path): #目录的路径和文件名拼接起来,得到了文件的绝路路

Python os.walk文件遍历

os.walk(top, topdown=True, onerror=None, followlinks=False) 可以得到一个三元tupple(dirpath, dirnames, filenames), 第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件. dirpath 是一个string,代表目录的路径, dirnames 是一个list,包含了dirpath下所有子目录的名字. filenames 是一个list,包含了非目录文件的名字. 这些名字不包含路径信息

Python入门之os.walk()方法

os.walk方法,主要用来遍历一个目录内各个子目录和子文件. os.walk(top, topdown=True, onerror=None, followlinks=False) 可以得到一个三元tupple(dirpath, dirnames, filenames), 第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件. dirpath 是一个string,代表目录的路径, dirnames 是一个list,包含了dirpath下所有子目录的名字. filenames 

Python 之 os.walk()

原文地址https://www.cnblogs.com/JetpropelledSnake/p/8982495.html          http://www.runoob.com/python/os-walk.html os.walk方法,主要用来遍历一个目录内各个子目录和子文件. os.walk(top, topdown=True, onerror=None, followlinks=False) 可以得到一个三元tupple(dirpath, dirnames, filenames),

Linux Ubuntu 16.04 python os.walk

os.walk(top,topdown=True,onerror=None,followlinks=False) os.walk()是python中内置(built-in)的目录树生成(directory tree generator)函数. 对于每一个在top目录下的子目录(包括top目录本身),该函数都会生成一个包含三个元素的元组(tuple): (dirpath, dirnames, filenames).(string,list,list) dirpath是目录名称(string),di