zoukankan      html  css  js  c++  java
  • python 编辑文件时路径问题解决方法:文件或者目录不存在、文件编辑后无法保存等(以编辑xml文件为例)

    1、获取工程所在根路径:根路径=os.path.dirname(os.path.abspath('__file__'))

    2、将获取的根路径和相对路径组合:组合路径=os.path.join(根路径,相对路径)

    3、规范化组合路径:os.path.normpath(组合路径)

    通过以上三步骤就可以完全解决文件定位问题;

    例子:

        def edit_xmlfile(self,filepath,filename,flag,newvalue):
            print u'--------------即将编辑xml文件--------------'
            print u'输入参数为:',filepath,filename,flag,newvalue
            filepathandfile=filepath+filename
            print 'filepathandfile=',filepathandfile
            #本地编辑文件
            print 'projectrootpath=',os.path.dirname(os.path.abspath('__file__'))  #工程(而非文件)所在根路径,精确到ZXJF/
            joinpath=os.path.join(os.path.dirname(os.path.abspath('__file__')),filepathandfile)
            normalpath=os.path.normpath(joinpath)
            print 'normalpath=',normalpath
            tree =parse(normalpath)
            root = tree.getroot()
            if flag=='filecoreconfigfile':
                print u'即将修改的内容为:',root.getchildren()[2].getchildren()[1].attrib
                hour,min,sec=newvalue.split('|')
                day=self.today[-2:]
                updatevalue=str(sec+' '+min+' '+hour+' '+day+' '+'* ?')
                print 'updatevalue=',updatevalue
                root.getchildren()[2].getchildren()[1].set('value',updatevalue)
                tree.write(normalpath)
                print u'>>>>>done!太棒了!修改后的内容为:',root.getchildren()[2].getchildren()[1].attrib
            print u'----------完成xml文件的编辑-----------'
  • 相关阅读:
    网络请求侦听工具
    再转动画实现
    转如何解决EXC_BAD_ACCESS错误
    关于Iphone开发得一些案例及常用知识(转过来的参考用)
    用uiwebview打开pdf,word,excel
    转 iphone开发资料汇总(很多实用的东东)
    设置uiview背景图的方法之一
    给状态条加上图标的代码
    xcode 4 下找EXC_BAD_ACCESS错误原因
    linux&unix常用命令
  • 原文地址:https://www.cnblogs.com/apple2016/p/6213681.html
Copyright © 2011-2022 走看看