简体   繁体   中英

python environment file open plus path

In environmental variables in system I have defined two variables:

A_home=C:\\install\\ahome B_home=C:\\install\\bhome

following script is written to read information from location of variable A close it, then open location of variable B and write it there, thing is script only works with precise path eg

C:\install\a\components\xxx\etc\static-data\myfile.xml
C:\install\b\components\xxx\etc\static-data\myfile.xml

problem is, that i need python to read path that is defined in env variable, plus common path like this: %a_home%\\a\\components\\xxx\\etc\\static-data\\myfile.xml`

so far i have this, and i cant move forward .... anyone have any ideas?? this script reads only exact path...

file = open('C:\install\a\components\xxx\etc\static-data\myfile.xml','r')
lines = file.readlines()
file.close()
file = open('C:\install\b\components\xxx\etc\static-data\myfile.xml','w')
for line in lines:
  if line!='</generic-entity-list>'+'\n':
    file.write(line)
file.write('<entity>XXX1</entity>\n')
file.write('<entity>XXX2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()

Try something like this:

import os
import os.path

home = os.getenv("A_HOME")
filepath = os.path.join(home, "components", "xxx", "etc", "static-data", "GenericEntityList.xml")
with open(filepath, 'r') as f:
    for line in f:
        print(line)

so finally success Thanks Tom, i was inspired by you ....

here goes

 import os
path1 = os.environ['SOME_ENVIRO1']
path2 = os.environ['SOME_ENVIRO2']
file = open(path1 +'\\components\\xxx\etc\\static-data\\GenericEntityList.xml', 'r')
lines = file.readlines()
file.close()
file = open(path2 +'\\components\\xxx\\etc\\static-data\\GenericEntityList.xml', 'w')
for line in lines:
  if line!='</generic-entity-list>'+'\n':
    file.write(line)
file.write('<entity>ENTITY1</entity>\n')
file.write('<entity>ENTITY2</entity>\n')
file.write('</generic-entity-list>\n')
file.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM