Skip to content

Instantly share code, notes, and snippets.

@X-Raym
Last active June 25, 2020 16:37
Show Gist options
  • Select an option

  • Save X-Raym/c5d840b842bab8bb28de6b0201269bef to your computer and use it in GitHub Desktop.

Select an option

Save X-Raym/c5d840b842bab8bb28de6b0201269bef to your computer and use it in GitHub Desktop.
Search and replace in text files from a folder and its subfolders without changing last modified date - Here is demo with .rpp and .rpp-bak files REAPER files
import sys
import os
from os import path
debug = False
#### USER INPUT ####
if debug:
dirName = "E:\\Bureau\\"
search = "F:\\Bureau\\SOUNDS"
replace = "F:\\Bureau\\SOUNDS-B"
else:
if len( sys.argv ) == 3: # Check if it has enough arguments
dirName = sys.argv[1] # Take first argument of the command
search = sys.argv[2]
replace = sys.argv[3]
else:
dirName = input("Folder?\n")
search = input("Search?\n")
replace = input("Replace?\n")
if os.path.isdir( dirName ) == False: # Does the folder exists?
print("Invalid inputs")
sys.exit("Folder doesn't exist.") # then kill the script
#### Process ####
# Get the list of all files in directory tree at given path
for (dirpath, dirnames, filenames) in os.walk(dirName):
for file in filenames:
if( file.lower().endswith(('.rpp', '.rpp-bak')) ):
# Get Path
file_path = os.path.join(dirpath, file)
print(file_path)
# Get Last Modified Date
last_modified_time = os.path.getmtime( file_path )
# Open File in Memory
f = open(file_path,'r', encoding="utf-8")
filedata = f.read()
f.close()
# Replace Content
newdata = filedata.replace( search, replace )
# Write File over Original
f = open(file_path,'w', encoding="utf-8")
f.write(newdata)
f.close()
# Restore Last Modified Date
os.utime( file_path, (last_modified_time, last_modified_time) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment