python脚本替换文件中的字符串
时间: 2023-10-23 16:08:36 浏览: 168
可以使用以下的Python脚本来替换文件中的字符串:
```python
def replace(file_path, old_str, new_str):
f = open(file_path, 'r+')
all_lines = f.readlines()
f.seek(0)
f.truncate()
for line in all_lines:
line = line.replace(old_str, new_str)
f.write(line)
f.close()
replace(file_path, old_str, new_str)
```
这个脚本会打开指定的文件,逐行读取文件内容,并将需要替换的字符串替换为新的字符串,然后将修改后的内容写回文件中。你只需要调用`replace`函数,并传入文件路径、需要被替换的字符串和新的字符串作为参数即可。请确保文件路径是正确的,并且你有足够的权限来读取和写入该文件。
#### 引用[.reference_title]
- *1* [python替换文件中字符串](https://blog.csdn.net/u013130865/article/details/78444363)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [Python文件字符串替换脚本](https://blog.csdn.net/liaoqing1999/article/details/107400295)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [python 脚本 替换文件中字符串](https://blog.csdn.net/weixin_43755117/article/details/109084956)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文