簡體   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