簡體   English   中英

Python-提取並修改Linux目錄中所有文件中的文件路徑

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

我有.sh文件和.json文件,其中提供了指向特定目錄的文件路徑,但是我應該繼續更改文件路徑,具體取決於運行python scipt的位置。

例如:我的.sh文件之一的內容是“ cd / home / aswany / BotStudioInstallation / databricks / platform / databricksastro”

我應該通過python代碼更改文件路徑,其中以下路徑

“ / home / aswany / BotStudioInstallation /”根據數據文件的位置不斷變化,

我嘗試了以下代碼:

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

函數replaceAll是:

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)

但是上面的代碼僅將“ home/holmes/BotStudioInstallation ”行替換到我登錄的當前目錄中,不能確定“ home/holmes/BotStudioInstallation ”是保持不變的唯一可能性,例如“ home/aswany/BotStudioInstallation “,” home/dev3/BotStudioInstallation “等,我為此想到了正則表達式。

請幫我

不確定我100%理解您的問題,但是也許我仍然可以提供幫助。

正如JF Sebastian指出的那樣,您可以使用相對路徑並刪除路徑的基礎部分。 使用./databricks/platform/devsettings.json可能就足夠了。 到目前為止,這是最優雅的解決方案。

如果由於某種原因而不是,則可以保留您需要訪問的目錄,然后在需要時將其追加到基本目錄中。 那應該允許您處理基本目錄中的更改。 盡管在某些情況下文件將被您自己的其他應用程序使用,但這可能不是一個選擇。

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

另外,這不是一個很好的解決方案,如果不使用正則表達式,則可以使用“模式”來始終替換。

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

然后,您便可以始終用基本目錄替換“ << _ replace_me _ >>”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM