如何在Python中读取和覆盖部分批处理文件

时间:2015-07-18 19:46:06

标签: python-2.7

我的批处理文件如下所示:

.....
set ARGS=%ARGS% /startDate:2015-07-15T15:20:00.000
set ARGS=%ARGS% /endDate:2015-07-15T17:30:00.000
set ARGS=%ARGS% /IDs:250
set ARGS=%ARGS% /values:10000,20000
.....

现在我想读它并用新日期覆盖它(当前开始和结束后1天)。如果我将其写入新文件,但下面的代码工作正常,但如果我尝试覆盖它则不起作用。有关如何修复它的想法吗?

WANTED = 19 #or however many characters you want after dates

with open('myfile.bat') as searchfile, open('mynewfile.bat', 'w') as outfile:


    for line in searchfile:
        left,sep,right = line.partition('startDate:')
        if sep: # True iff 'Figure' in line
            startdatestr = (right[:WANTED])
            startdate = datetime.strptime(startdatestr, "%Y-%m-%dT%H:%M:%S")
            newstartdate = startdate + timedelta(days=1)
            newstartdatestr = newstartdate.strftime("%Y-%m-%dT%H:%M:%S")
            line = line.replace(startdatestr, newstartdatestr)  


        left,sep,right = line.partition('endDate:')
        if sep: # True iff 'Figure' in line
            enddatestr = (right[:WANTED])
            enddate = datetime.strptime(enddatestr, "%Y-%m-%dT%H:%M:%S")
            newenddate = enddate + timedelta(days=1)
            newenddatestr = newenddate.strftime("%Y-%m-%dT%H:%M:%S")
            line = line.replace(enddatestr, newenddatestr)  
        outfile.write(line)  

1 个答案:

答案 0 :(得分:0)

当你在开放()'部分,您的文件仍处于打开状态,因此您无法覆盖它。将内容和修改存储在变量中,并使用open()' part,以便文件句柄关闭。

然后打开文件进行写入并将数据输出到其中。