I have a lot of files inside of directory containing some paths. Need to go through all files, and replace first part of the "path" with other one which is I previously got. Have in mind that 'sw' will always be a border between those 2 parts after split.
So inside of the files paths are:
E:\p\folder\folder2\sw\first_step\step1\step2\final
E:\p\folder\folder2\sw\second_step\step1\step2\final
E:\p\folder\folder2\sw\second_step\step56\step333\final
E:\p\folder\folder2\sw\second_step\step1\step2\final
etc
My code:
def findReplace(directory, find, replace, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with open(filepath) as f:
s = f.read()
s = s.replace(find, replace)
with open(filepath, "w") as f:
f.write(s)
base_dir = 'F:/Users/User1/Folder/'
path_to_files = '/folder1/folder2/files/'
directory = os.listdir(os.path.join(base_dir, path_to_includes_appl))
for file in directory:
if file == None: continue
with open (file, 'r') as f:
content = f.read().split('\n')
for line in content:
if not line: continue
# Idea here is to sepeare part we need to replace with part that has to stay
old_path, path_to_file = line.split('sw\\')
findReplace(str(directory), old_path, base_dir, ".c")
Final output should be:
F:\Users\User1\Folder\sw\first_step\step1\step2\final
F:\Users\User1\Folder\second_step\step1\step2\final
F:\Users\User1\Folder\second_step\step56\step333\final
F:\Users\User1\Folder\second_step\step1\step2\final
NOTE: Please ignore diff between "/" and "\"
Anyone has idea what am I doing wrong, or has some better idea of how to achieve this? Thanks!
EDIT:
This is my new code:
base_dir = 'F:/Users/User1/Folder/'
path_to_includes_appl = '/folder1/folder2/files/'
# directory = os.listdir(os.path.join(base_dir, path_to_includes_appl))
directory_path = (os.path.join(base_dir, path_to_includes_appl))
directory = os.listdir(directory_path)
for file in directory:
with open (directory_path+file, 'r') as f:
content = f.readlines()
for line in content:
old_path, path_to_file = line.split('sw\\')
findReplace(directory_path, old_path, base_dir, ".c")
When I run this, nothing happens, no error but also no updated files