else/Toolbox/contentreplace.py

41 lines
958 B
Python
Raw Normal View History

2019-03-22 21:51:02 +00:00
import glob
2016-11-18 06:24:52 +00:00
import codecs
import sys
2019-03-22 21:51:02 +00:00
filenames = glob.glob(sys.argv[1])
2016-11-18 06:24:52 +00:00
replace_from = sys.argv[2]
replace_to = sys.argv[3]
try:
automatic = sys.argv[4] == '-y'
except IndexError:
automatic = False
replace_from = codecs.decode(replace_from, 'unicode_escape')
replace_to = codecs.decode(replace_to, 'unicode_escape')
2019-03-22 21:51:02 +00:00
def contentreplace(filename):
f = open(filename, 'r', encoding='utf-8')
with f:
content = f.read()
2016-11-18 06:24:52 +00:00
2019-03-22 21:51:02 +00:00
occurances = content.count(replace_from)
if occurances == 0:
print('No occurences')
return
2016-11-18 06:24:52 +00:00
2019-03-22 21:51:02 +00:00
print('Found %d occurences.' % occurances)
if automatic:
permission = 'y'
else:
permission = input('Replace? ')
if permission.lower() not in ['y', 'yes']:
exit()
2016-11-18 06:24:52 +00:00
2019-03-22 21:51:02 +00:00
content = content.replace(replace_from, replace_to)
2016-11-18 06:24:52 +00:00
2019-03-22 21:51:02 +00:00
f = open(filename, 'w', encoding='utf-8')
with f:
f.write(content)
for filename in filenames:
contentreplace(filename)