【发布时间】:2019-12-17 02:55:13
【问题描述】:
我有一个输入文本文件如下,这个保存为12.txt:
[(442, 165), (442, 184), (487, 165), (487, 184)],english
我的目标是从这个文件中删除所有特殊字符并覆盖它:我正在使用下面的 python 脚本 :
import os
import numpy as np
import math
import cv2 as cv
#path = '/media/D/code/OCR/text-detection-ctpn/data/mlt_english+chinese/image'
gt_file = '12.txt'
with open(gt_file, 'r+') as f:
for line in f.readlines():
line = line.replace("[", "")
line = line.replace("(", "")
line = line.replace(")", "")
line = line.replace("]", "")
line = line.replace(" ", "")
f.write(line)
但是它给了我这个输出:
[(234, 162), (234, 183), (307, 162), (307, 183)],english 234,162,234,183,307,162,307,183,english
我不希望像上面显示的那样附加输出我希望输出覆盖 12.txt。运行 python 脚本后的 12.txt 文件应如下所示:
234,162,234,183,307,162,307,183,english
我已经推荐了Python replace and overwrite instead of appending,但我缺少一些东西
【问题讨论】:
-
打开文件时是否使用'w+'而不是'r+'作为选项不起作用?
-
@TUIlover
w+截断文件,因此 OP 将无法读取数据。
标签: python