简体   繁体   中英

Python - extract and modify a file path in all files in a directory in linux

I have files .sh files and .json files in which there are file paths given to point to a specific directory, but I should keep on changing the file path, depending on where my python scipt is run.

eg:content of one of my .sh file is "cd /home/aswany/BotStudioInstallation/databricks/platform/databricksastro"

and I should change the file path via python code where the following path

"/home/aswany/BotStudioInstallation/" keep on changing depending on where databicks is located,

I tried the following code:

replaceAll(str(self.currentdirectory)+
    "/databricks/platform/devsettings.json",
    "/home/holmes/BotStudioInstallation",self.currentdirectory)

and function replaceAll is:

def replaceAll(self,file,searchExp,replaceExp):
     for line in fileinput.input(file, inplace=1):
         if searchExp in line:
            line = line.replace(searchExp,replaceExp)
         sys.stdout.write(line)

but above code only replaces a line " home/holmes/BotStudioInstallation " to the current directory I am logged in,bt it cannot be sure that " home/holmes/BotStudioInstallation " is the only possibility it keep on changing like " home/aswany/BotStudioInstallation "," home/dev3/BotStudioInstallation " etc ,I thought of regular expression for this.

please help me

Not sure I 100% understood your issue, but maybe I can help nonetheless.

As pointed out by JF Sebastian , you can use relative paths and remove the base part of the path. Using ./databricks/platform/devsettings.json might be enough. This is by far the most elegant solution.

If for any reason it is not, you can keep the directory you need to access, then append it to the base directory whenever you need it. That should allow you to deal with changes in the base directory. Though in the case the files will be used by other applications than your own, that might not be an option.

dir = get_dir_from_json()
dir_with_base = self.currentdirectory + dir

Alternatively, not an elegant solution though, without using regex you can use a "pattern" to always replace.

{
  "directory": "<<_replace_me_>>/databricks/platform"
}

Then you know you can always replace "<<_replace_me_>>" with the base directory.

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