0

I am writing a python script but open to doing the same in batch script to replace line strings. I have a directory which has few files in it and have a file.json in a different directory. I want to replace a line in file.json with the full path of the files from the other directory. i.e the line would be overwritten every time with list of file path.

This is what I have done so far, cannot get the list to replace the string yet.

Code:

import shutil
import re
import os

origin_path = '/home/download/project/'
Source_files='/home/download/automate_proj/file.json'
target_file = /tmp/file.json

for file in os.listdir(origin_path):
   for f in file:
      f = open(file, 'r')
      for line_org in f.read():
         shutil.copy(line_org)
 
with open(source_file, 'r') as sfile:
   with open(target_file,'w') as outfile:
     for line in sfile:
        if "FILE PATH PLACEHOLDER" in line:
            line = line.replace('FILE PATH PLACEHOLDER', line_org)
        outfile.write(line) 

print "DONE"

Example, directory and its files

$ pwd
/home/download

/home/download/new.txt
/home/dowload/new1.txt
/home/download/new2.txt
/home/download/new3.txt

Example:

file.json

"dataSchema" : {
    "dataSource" : "FILE PATH PLACEHOLDER",
        "parser" : {
            "format" : "json"
        }
}

So I want to replace or overwrite file.json line "FILE PATH PLACEHOLDER" with list of file paths from the directory each time the code runs.

Expected outcome

"dataSource": "/home/downloads/new.txt" 

The next loop run would be:

"dataSource": "/home/downloads/new1.txt"

"dataSchema" : {
    "dataSource" : "/home/downloads/new2.txt",
        "parser" : {
            "format" : "json"
        }
}
Nic3500
  • 8,144
  • 10
  • 29
  • 40
mc940
  • 9
  • 3
  • Your file.json and expected results aren't valid json... – Shawn Aug 28 '20 at 15:01
  • In your `line.replace(...)`, you use the `line_org` variable. That variable only exists in the context of the `for line_org in f.read():`. So when you get to the `line.replace(...)`, it will never do anything. Unless the indentation is wrong in your question...? – Nic3500 Aug 29 '20 at 03:27

0 Answers0