我的views.py文件代码:
#!/usr/bin/python
from django.template import loader, RequestContext
from django.http import HttpResponse
#from skey import find_root_tags, count, sorting_list
from search.models import Keywords
from django.shortcuts import render_to_response as rr
def front_page(request):
if request.method == 'POST' :
from skey import find_root_tags, count, sorting_list
str1 = request.POST['word']
fo = open("/home/pooja/Desktop/xml.txt","r")
for i in range(count.__len__()):
file = fo.readline()
file = file.rstrip('\n')
find_root_tags(file,str1,i)
list.append((file,count[i]))
sorting_list(list)
for name, count1 in list:
s = Keywords(file_name=name,frequency_count=count1)
s.save()
fo.close()
list1 = Keywords.objects.all()
t = loader.get_template('search/results.html')
c = RequestContext({'list1':list1,
})
return HttpResponse(t.render(c))
else :
str1 = ''
list = []
template = loader.get_template('search/front_page.html')
c = RequestContext(request)
response = template.render(c)
return HttpResponse(response)
我在函数 find_root_tags(file,str1,i)
中发送的变量"file"有一个 xml 文件的名称。这个文件出现在我的桌面上,这段代码写在我的 django 应用程序的 views.py 文件中,所以它无法打开那个文件。我该如何打开该文件,因为 xml.txt 包含要读取然后打开的相似文件名。简而言之,我如何将文件参数发送为:
file1 = '/home/pooja/Desktop/<filename>'
在这里<filename>
等于存储在变量 file
中的值并最终能够将其称为:
find_root_tags(file1, str1, i)
//////////////////////////////////////////////////////////////////////////////////////
澄清:
1)请引用变量“file”,你可以看到我存储的是xml.txt读取的内容。
2)xml.txt 包含 xml 文件名。 views.py 文件是 django 应用程序的一部分,无法打开这些文件,因为它们存在于桌面上。
3) 我的问题是如何修改和发送包含文件名并附加绝对路径的文件变量:
'/home/pooja/Desktop/filename'
这样做会打开桌面上的文件。
最佳答案
试试这个:
pathh='/home/pooja/Desktop/' #set the base path
fo = open("/home/pooja/Desktop/xml.txt")
for i in range(len(count)): #use len(count)
file = fo.readline()
file = file.strip() #use strip()
find_root_tags(pathh+file,str1,i) #base path+file
mylist.append((file,count[i])) #using 'list' as a variable name is not good
关于python - 错误 : file i/o in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11329722/