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文件的编辑-----------'
原文地址:https://www.cnblogs.com/apple2016/p/6213681.html