尝试修改文本文件,但旧部分仍然存在,并且存在重复。要更改的原始.txt文件包含:
START_DATE 01/01/2014
START_TIME 02:00:00
REPORT_START_DATE 01/01/2014
REPORT_START_TIME 02:00:00
END_DATE 01/01/2014
END_TIME 03:00:00
我使用了带有列表的txt文件来搜索(START_DATE,START_TIME,REPORT_START_DATE,REPORT_START_TIME,END_DATE,END_TIME)和第二个txt来替换这些项目。虽然代码替换了正确的项目,但旧值的一半会在新行上停留,并且不会被删除?由于REPORT_START_TIME中的短语START_TIME,还存在重复。有什么建议?我一直在尝试修改readlines(),read()。split(' \ n'),但还没有成功。到目前为止,我从下面的代码中得到的最接近的是:
START_DATE 02/02/2002
01/01/2014
START_TIME 02:02:02
02:00:00
REPORT_START_DATE 02/02/2002
02/02/2002
01/01/2014
REPORT_START_TIME 02:02:02
02:02:02
02:00:00
END_DATE 02/03/2002
01/01/2014
END_TIME 03:03:03
03:00:00
到目前为止的代码:
findlines = open('new_date_time_list.txt').read().split('\n')
replacelines = open('new_date_time.txt').readlines()
find_replace = dict(zip(findlines, replacelines))
with open('text_ammend.txt') as data:
with open('new_data.txt', 'w') as new_data:
for line in data:
for key in find_replace:
if key in line:
line = line.replace(key, find_replace[key])
new_data.write(line)
答案 0 :(得分:0)
我不会给你代码,但是通用的解决方案,每一步都包含关键词,只需添加python并在google中搜索它或在这里很容易。
或者与我们分享您的代码
步骤:
#1 Open file and read it line by line
#2 Split each line in array, delimiter space
#3 If array lenght != 0
##4 If array[0] == START_DATE
###4 array[1] = Your_new_date
###4 array[1] = Your_new_time
#5 Register and close the file