[英]How can I write a function for getting all the files without repeating the path each time?
My complete function: 我完整的功能:
def Unzip(APP_NAME, ASSETS_PATH):
nameDir=ASSETS_PATH+"\\unzip\\"
print "[INFO] Unzipping"
a=1
files=[]
file_name = APP_NAME.split("/")
file_name = file_name[-1]
out_dir = ASSETS_PATH+"/unzip/"+file_name+"_"+datetime.datetime.now().strftime("%d%m%Y%H%M%S")
try:
files = []
with zipfile.ZipFile(APP_NAME, "r") as z:
for fileinfo in z.infolist():
dat = z.open(fileinfo.filename, "r")
filename = fileinfo.filename
if not isinstance(filename, unicode):
filename = unicode(fileinfo.filename, encoding="utf-8", errors="replace")
files.append(filename)
outfile = os.path.join(out_dir, filename)
if not os.path.exists(os.path.dirname(outfile)):
try:
os.makedirs(os.path.dirname(outfile))
except OSError as exc:
if exc.errno != errno.EEXIST:
print "\n[WARN] OS Error: Race Condition"
if not outfile.endswith("/"):
with io.open(outfile, mode='wb') as f:
f.write(dat.read())
dat.close()
a=a+1
print a
return files, out_dir
The structure of my files is like this: 我的文件结构如下:
|--a
| |--a
| |--b
| | |--a.txt
| |
| |--c
|
|--b
| |--a
| |--a.txt
| |--b.txt
|
|--c
| |--a.txt
| |--b.txt
|
|--d
Where a.txt and b.txt are filse and a , b , c , d are directories. 其中a.txt和b.txt是filse,而a , b , c和d是目录。
I want to create a dict that takes into consideration the depth of the files in the tree. 我想创建一个考虑树中文件深度的字典。
How can I write a function for getting all the files but without repeating the path each time ? 我如何编写一个函数来获取所有文件, 而又不必每次都重复路径 ?
All inside the FOR-cycle that already exists. 所有已经存在的FOR周期内。
The result should be like when I enter into the properties of object. 结果应该类似于当我输入对象的属性时。
您可以使用os.walk("root path ")
This function return all files without repeat as a list of string 此函数返回所有文件,而不重复作为字符串列表
def get_files(path1):
res =[]
for path, subdirs, files in os.walk(path1):
for name in files:
res.append(os.path.join(path, name))
return list(set(res))
list(set(res))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.