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

2024-10-01 15:39:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须读取一个目录的子文件夹名称,并将其写入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")

Tags: 代码uiosrequestopenlistfiledhl
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:40

您可以使用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)

相关问题 更多 >

    热门问题