I have the current script included below that goes into a file with extension .las and replaces certain strings with others (ie.: cat -> kitten, dog -> puppy).
All I want is to add in a functionality into this script that would rename ANY .las file to a certain name in the current directory when I run the script (ie.: *.las -> animals.las).
I would drag a single file into this directory, run the script, which performs the text replacement and the rename and then move the file out of the current directory. So for this script, I don’t care that it would rewrite multiple .las files to a single name.
# read a text file, replace multiple words specified in a dictionary
# write the modified text back to a file
import re
import os
import time
# the dictionary has target_word:replacement_word pairs
word_dic = {
'cat' : 'kitten',
'dog' : 'puppy'
}
def replace_words(text, word_dic):
"""
take a text and replace words that match a key in a dictionary with
the associated value, return the changed text
"""
rc = re.compile('|'.join(map(re.escape, word_dic)))
def translate(match):
return word_dic[match.group(0)]
return rc.sub(translate, text)
def scanFiles(dir):
for root, dirs, files in os.walk(dir):
for file in files:
if '.las' in file:
# read the file
fin = open(file, "r")
str2 = fin.read()
fin.close()
# call the function and get the changed text
str3 = replace_words(str2, word_dic)
# write changed text back out
fout = open(file, "w")
fout.write(str3)
fout.close()
#time.sleep(1)
scanFiles('')
I pasted the script together from online examples so I don’t know all the inner workings of it, so if anyone has a more elegant/efficient way of doing what this script is doing, I am open to changing it.
If you want to end up with a single file named animals.las containing the contents of *.las, then you can change the scanFiles function to open animals.las at the start of the loop, write the translated output of each *.las file to animals.las, and then close animals.las: