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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值