python-2.7 - 从文件python读取指令
问题描述
我有这个代码:
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
我该怎么做?
解决方案
推荐阅读
- java - 如何忽略 RDD 字符串的一部分进行操作
- javascript - 使用 JSON 创建表格并对其进行样式化
- c++ - glm c++ 在每个循环上输出差值
- android - 使用自签名证书签署应用程序是否会影响哪些 Android 设备可以在 Play 商店中看到该应用程序?
- list - 列出埃隆马斯克推文情感分析中超出范围的索引
- node.js - WebRTC 对等服务器连接
- python - 如何在不重新运行程序的情况下在 tkinter 表上显示新的添加数据?
- rust - 如何将函数存储在结构中,然后在其他地方使用?
- python - 在我的情况下,如何使用 sqlite3 更新 UNIQUE 值?
- math - 如何找到一个整数乘数以达到 10 的幂?