我有此代码:
import os
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename, 'r') as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
else:
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
s = s.replace(old_string, new_string)
f.write(s)
path = raw_input("Enter the file's full path: ")
old = raw_input("String to change: ")
new = raw_input("change to: ")
print "********************************"
print "**** WORKING... PLEASE WAIT ****"
print "********************************\n"
for file in os.listdir(path):
filename = os.path.join(path,file)
inplace_change(filename, old, new)
os.system("pause")
如您所见,代码将文件中的子字符串替换为另一个子字符串。我希望我的代码按照文本文件中的指示更改文本,例如“指令文件”要更改的内容。 文本文件将是:
"old_string" "new_string"
"old_string" "new_string"
"old_string" "new_ string"
结果将是目录中的所有文件将所有old_string更改为new_string
我该怎么办?