繁体   English   中英

在文本文件中替换单词-python 2.7

[英]Replacing word in text file- python 2.7

我有2个文件,如下所示

分行数据:

open bus from 2311 to 3223 ck 1
open bus from 4321 to 3783 ck 1
.
.
.

我有大约100个这样的分支

档案中:

contingency 'b2_452'
QQQQQQQQ
open bus from 4321 to 3784 ck 1
end
.
.
.

我大概有200种意外情况

我正在尝试获得如下所示的输出

排除的输出文件:

文件1

contingency 'b2_452'
open bus from 2311 to 3223 ck 1
open bus from 4321 to 3784 ck 1
end

文件2

contingency 'b2_452'
open bus from 4321 to 3783 ck 1
open bus from 4321 to 3784 ck 1
end

这是我的代码

infile = open('Contingency.txt').read()
Brachdata = open('BranchData.txt', 'r')
i = 0
for branchline in Brachdata:
    replace1 = branchline
    i = i + 1
    outputfile = open('file' + str(i) +'.txt', 'w')
    for line in infile:
        outputfile.write(line.replace('QQQQQQQQ', replace1))
outputfile.close()

我是python编程的新手,不确定我哪里出错了。 这段代码正在创建我的infile的两个副本...而不用该行替换QQQQQQQQ。

我想出了问题所在..这是更新的代码

f2 = open('Contingency.txt', 'r')
f1 = open('Contingency new.txt', 'w')

for line in f2:
    if 'QQQQQQQQ' in line:
        f1.write("    @")
    else:
        f1.write(line)
f1.close()

Brachdata = open('BranchData.txt', 'r')
infile = open('Contingency new.txt').read()

i = 0
for branchline in Brachdata:
    replace1 = branchline
    i = i + 1
    outputFile = open('Contingency' + str(i) +'.txt', 'w')
    for line in infile:
        if '@' in line:
            outputFile.write(replace1)
        else:
            outputFile.write(line)
Brachdata.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM