如何在Django视图中读取目录的子文件夹并写入文本文件

时间:2019-05-17 09:50:55

标签: python django user-interface django-views

我必须读取目录的子文件夹名称,然后在django视图中将其写入文本文件

我已经尝试了以下代码,但是UI并未加载此代码。

def start(request):
    try:
    cwd=os.getcwd()
    os.chdir("/Volumes/localStorage2/DHLData/DHLs")
    subfolders=os.listdir()
    os.chdir(cwd)
    file = open("/Volumes/localStorage2/DHL/UI/dhl_list.txt", "w")
        for i in subfolders:    
            file.write(i)
        file.close()

我已经编写了视图的全部代码

def start(request):
    try:
    #cwd=os.getcwd()
    # os.chdir("/Volumes/localStorage2/DHLData/DHLs")
    #subfolders=os.listdir()
    # os.chdir(cwd)
    # file =open("/Volumes/localStorage2/DHL/UI/dhl_list.txt","w")
    # for i in subfolders:  
        # file.write(i)
        # file.write("\n")
    # file.close()
    dhl_list = []    
    if os.path.exists("/Volumes/localStorage2/DHLData/DHLs"):        
        with open("/Volumes/localStorage2/DHL/UI/dhl_list.txt") as dhlListFile:
            for dhl_name in dhlListFile:
                dhl_list.append(dhl_name)    
    return render(request, "i3_flow.html",{"dhl_list":dhl_list})
except Exception:
    print(traceback.format_exc())    
    return render(request, "i3_flow.html")

1 个答案:

答案 0 :(得分:0)

您可以使用globos(在标准库中)尝试以下操作: r_subfolders包含其相对名称,a_subfolders包含其绝对名称。

import os
import glob

my_path = "/Volumes/localStorage2/DHLData/DHLs"

r_subfolders = []
a_subfolders = []

for filename in glob.glob("%s/*" % my_path):
    if os.path.isdir(filename):
        r_subfolders += [filename[len(my_path)+1:]]
        a_subfolders += [filename]

print(r_subfolders)
print(a_subfolders)