Jan-09-2020, 08:27 AM
Hi,
I am trying to update a *.msh file by finding a 'find_word' and replace it with rep_word'.
I wrote a program to read an input csv file where I will be giving these fields. - file_type(values input are msh,mshs), folder_path(path where files are to be searched for the word and replaced), sub_directory(ignore as of now), find_word(the workd which needs to be searched), rep_word(the word to be replaced).
input file
I am trying to update a *.msh file by finding a 'find_word' and replace it with rep_word'.
I wrote a program to read an input csv file where I will be giving these fields. - file_type(values input are msh,mshs), folder_path(path where files are to be searched for the word and replaced), sub_directory(ignore as of now), find_word(the workd which needs to be searched), rep_word(the word to be replaced).
import os import re import csv """Replace a word in the file with the replace word and writes into the file""" def check_and_replace(file, find_word, rep_word): rfile = open(file, 'rt') string = rfile.read() rfile.close() string = re.sub(find_word, rep_word, string) wfile = open(file, 'wt') wfile.write(string) wfile.close() """Reads the input test file and gets the values for file type, folderpath, subdirectory value, find word and replace word""" """file_type will have values like msh or mshs""" """folder_path will have value of the folder where replace is done""" """find word is the search word and rep_word is the word to be replaced""" with open('test csv.csv', 'r') as csv_file: next(csv_file) csv_reader = csv.reader(csv_file) for line in csv_reader: file_type = line[0] folder_path = line[1] sub_directory = line[2] find_word = line[3] rep_word = line[4] for path, subdirs, files in os.walk(folder_path): for file in files: if file.endswith(file_type): new_file_name = os.path.join(path, file) check_and_replace(new_file_name, find_word, rep_word)sample msh file
input file