django中的文件读取错误 [英] File reading Error in django
问题描述
以下是读取文件的行&在django中下载:
def下载(请求):file_name = request.GET.get('file_name','')path_to_file ="C:\ Users \ CV_Uploads \ uploadfiles \ uploadfiles" +"\\" + file_namefileanme = open('r'.path_to_file,"rb")#**这里错误**mimetype = mimetypes.guess_type('path_to_file')[0]如果不是mimetype:mimetype ="application/octet-stream"响应= HttpResponse(fileanme.read(),mimetype = mimetype)response ["Content-Disposition"] =附件;文件名=%s"%os.path.split(path_to_file)[1]返回响应
问题:可以很好地处理硬编码的值,但是现在我通过将 path_to_file与file_name
结合起来使此代码动态化.它说:/download/中的 AttributeError....'str'对象没有属性'path_to_file'
如何解决此属性错误?
好吧,该代码显然是错误的.如错误所言,您正在使用字符串"r"
,并使用点号在其上调用 path_to_file
属性,该属性不存在.>
我不确定 r
应该做什么.没有它,它应该可以正常工作:
fileanme = open(path_to_file,"rb")
Here are the lines to read file & download in django :
def download(request):
file_name =request.GET.get('file_name', '')
path_to_file = "C:\Users\CV_Uploads\uploadfiles\uploadfiles" + "\\" + file_name
fileanme = open('r'. path_to_file , "rb") # **ERROR HERE**
mimetype = mimetypes.guess_type('path_to_file')[0]
if not mimetype: mimetype = "application/octet-stream"
response = HttpResponse(fileanme.read(), mimetype=mimetype)
response["Content-Disposition"]= "attachment; filename=%s" % os.path.split(path_to_file)[1]
return response
Problem:
Was working fine with hardcoded values but now as i make this code dynamic by joining path_to_file with file_name
. It says: AttributeError at /download/ . . . .'str' object has no attribute 'path_to_file'
How to solve this attribute error?
Well, that code is clearly wrong. As the error says, you're taking the string "r"
, and using the dot notation to call a path_to_file
attribute on it, which doesn't exist.
I'm not sure what that r
is supposed to be doing at all. It should work fine without it:
fileanme = open(path_to_file , "rb")
这篇关于django中的文件读取错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!