35 lines
1.0 KiB
Python
35 lines
1.0 KiB
Python
|
|
import os
|
|||
|
|
|
|||
|
|
|
|||
|
|
def replace_ship_in_txt_files(directory):
|
|||
|
|
"""
|
|||
|
|
遍历指定目录下的所有txt文件,将其中的'ship'替换为'civil_ship'
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
directory (str): 要处理的目录路径
|
|||
|
|
"""
|
|||
|
|
# 获取目录下所有文件
|
|||
|
|
all_files = os.listdir(directory)
|
|||
|
|
|
|||
|
|
# 筛选出txt文件
|
|||
|
|
txt_files = [f for f in all_files if f.endswith('.txt')]
|
|||
|
|
|
|||
|
|
for filename in txt_files:
|
|||
|
|
filepath = os.path.join(directory, filename)
|
|||
|
|
|
|||
|
|
# 读取文件内容
|
|||
|
|
with open(filepath, 'r', encoding='utf-8') as file:
|
|||
|
|
content = file.read()
|
|||
|
|
|
|||
|
|
# 替换字符串
|
|||
|
|
modified_content = content.replace('civil_ship', 'civil_ship 1')
|
|||
|
|
|
|||
|
|
# 写回文件
|
|||
|
|
with open(filepath, 'w', encoding='utf-8') as file:
|
|||
|
|
file.write(modified_content)
|
|||
|
|
|
|||
|
|
print(f"已处理文件: {filename}")
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 使用示例
|
|||
|
|
replace_ship_in_txt_files(r'R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\C-人工检查\删除空标注') # 请替换为你的目录路径
|