您的位置:首页 > 编程语言 > Python开发

python小功能

2021-12-19 15:24 756 查看

 

django实现将linux目录和文件名列出来

def index(request):
obj=models.USER.objects.all()

fileroot = 'd:\machangwei'
fli = os.listdir(fileroot)
print(fli)
dirdic = {}
filedic = {}
for i in fli:
file = os.path.join(fileroot, i)
if os.path.isdir(file):
dirdic[i] = file
print('d:', file)
else:
filedic[i] = file
print('f:', file)

return render(request,'index.html',{"obj":obj,'dirdic':dirdic,'filedic':filedic})
视图函数
<h2>根目录下的目录和文件:</h2>
{% for k,v in dirdic.items %}
<a href="" srcmcw="{{ v }}">{{ k }}</a><br>
{% endfor %}
{% for k,v in filedic.items %}
<a href="" srcmcw="{{ v }}">{{ k }}</a><br>
{% endfor %}
前端展示

def  listfile(request):
'''
1、要获取前端传来的fp,当前目录绝对路径,跟据这个参数来os list目录,这里暂且用的是全路径
2、
:param request:
:param fname:
:return:
'''
# print(fname) #venv
#print(request.GET) #<QueryDict: {'fp': ['d:\\machangwei\\whl']}>
fp=request.GET.get('fp',['m'])  #d:\machangwei\venv  当前目录绝对路径
fn=request.GET.get('fn','')  #当前目录名字,f子文件名字,这里貌似没用到
# zfp=os.path.join(fp,fn) #当前目录下子文件绝对路径,我们传给后端的是allf,所以这个是错误的,新页面中的fp需要
# 当前目录名字fp拼接当前目录下单个文件的名字
print(request.GET)
print('fp:',fp) #fp: d:\machangwei\venv
print('fn:',fn) #fn: venv
if os.path.isdir(fp):
allf=os.listdir(fp) #['Include', 'Lib', 'pip-selfcheck.json', 'pyvenv.cfg', 'Scripts'] #列出当前目录下所有文件
print(allf)

return render(request,'listfile.html',{'allf':allf,'fn':fn,'fp':fp})
视图函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>{{ fp }}\{{ f }}目录下的目录和文件:</h2>
<p><a href="/index/">返回首页</a></p>
{% for f in allf %}
<a href="/listfile/?fp={{ fp }}\{{ f }}&fn={{ f }}" name="{{ fp }}/{{ f }}">{{ f }}</a><br>
{% endfor %}

</body>
</html>
前端程序 效果展示:

else:
file = open('%s'%fp, 'rb')
response = HttpResponse(file)
response['Content-Type'] = 'application/octet-stream'  # 设置头信息,告诉浏览器这是个文件
response['Content-Disposition'] = 'attachment;filename="%s"'%fn
return response
程序

 

 

 

 

 

 

 

 

 

文件下载参考:https://www.jb51.net/article/135951.htm

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: