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"
}
}