![](/img/trans.png)
[英]How can I write a repeating movement function without using global variables?
[英]How can I write a function for getting all the files without repeating the path each time?
我完整的功能:
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
我的文件結構如下:
|--a
| |--a
| |--b
| | |--a.txt
| |
| |--c
|
|--b
| |--a
| |--a.txt
| |--b.txt
|
|--c
| |--a.txt
| |--b.txt
|
|--d
其中a.txt和b.txt是filse,而a , b , c和d是目錄。
我想創建一個考慮樹中文件深度的字典。
我如何編寫一個函數來獲取所有文件, 而又不必每次都重復路徑 ?
所有已經存在的FOR周期內。
結果應該類似於當我輸入對象的屬性時。
您可以使用os.walk("root path ")
此函數返回所有文件,而不重復作為字符串列表
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.