python - 错误 : file i/o in python

标签 python django linux file ubuntu-10.04

我的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/

相关文章:

python - Pycares 的构建轮 (Setup.Py) 错误

python - 在 anaconda 错误上安装 pygraphviz

python - Django - 使用外部脚本从 url 下载图像并将其插入 imageField

python - 起始页上的 Django 注册表单,无需重定向到登录页

javascript - 同一域中 IE9 中的 Script5 访问被拒绝

linux - RHEL 中 "members"的等效命令

python - 需要在 python 中使用字符串索引的帮助

python - 在 python 中使用字符串扩展切片

linux - 迭代 cpu 事件运行队列列表 sched.h

c - 这个代码段告诉我什么?