【Python】如何在文件夹里批量替换文本中的内容?
生活随笔
收集整理的這篇文章主要介紹了
【Python】如何在文件夹里批量替换文本中的内容?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.Introduction
用深度學習做目標檢測時,有時候標簽需要批量替換,這時一個批量處理的代碼就很關鍵~
2.Materials and methods
下面對文件夾中的所有 xml 文件中的指定內容進行替換,txt 文件同理。
代碼如下:
# -*- coding: utf-8 -*- """ Created on Fri Dec 25 19:07:33 2020@author: YaoYee """ #coding=utf-8 import osdef listFiles(dirPath):fileList = []for root, dirs, files in os.walk(dirPath):for fileObj in files:fileList.append(os.path.join(root, fileObj))return fileListdef main():fileDir = "C:/Users/YaoYee/Desktop/val"#regex = ur'FUNC_SYS_ADD_ACCDETAIL'fileList = listFiles(fileDir)fileList = listFiles(fileDir)for fileObj in fileList:f = open(fileObj, 'r+')all_the_lines = f.readlines()f.seek(0)f.truncate()for line in all_the_lines:# e.g. 'dog' is original name, 'cat' is the new one.f.write(line.replace('dog', 'cat'))f.close()if __name__ == '__main__':main()3. Results and discussion
下面以把 dog 換成 cat 為例~
如果要同時替換多個內容文本呢?
用下面的代碼替換下就ok了:
f.write(line.replace('dog', 'cat').replace('man', 'boy'))4. Conclusion
Done is better than perfect.
猜你喜歡:👇🏻
?【Python】如何在文件夾里批量修改文件名(001-100)?
?【Python】如何在文件夾里批量分割圖片?
?【Python】隨機劃分數據集并生成VOC格式列表
總結
以上是生活随笔為你收集整理的【Python】如何在文件夹里批量替换文本中的内容?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何批量在文件夹中建立php,怎么批量创
- 下一篇: 如何通过控制台访问openstack实例