Python打印全文文件

时间:2016-05-25 01:19:10

标签: python replace text-files

我想替换"示例"在textfile2.txt上,带有textfile1.txt中的单词列表,直到列表用完或所有"示例"已全部被替换然后我想显示整个完成的文本。

我该怎么做?

textfile1.txt

user1
user2

textfile2.txt

URL GOTO=https://www.url.com/example
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/example
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

当前代码:

with open('textfile1.txt') as f1, open('textfile2.txt') as f2:
    for l, r in zip(f1, f2):
        print(r[:r.find('/example') + 1] + l)

结果它给了我:

URL GOTO=https://www.instagram.com/user1

user2

目标:

URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/user2
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

1 个答案:

答案 0 :(得分:3)

这是我的解决方案:

with open('t1.txt') as f1, open('t2.txt') as f2:
    url_info = f2.read().split('\n\n')
    users = f1.read().split('\n')
    zipped_list = zip(users, url_info)
    for item in zipped_list:
        print item[1].replace('example', item[0])+"\n"

<强>更新 这需要导入itertools

import itertools
with open('t1.txt') as f1, open('t2.txt') as f2:
    url_info = f2.read().split('\n\n')
    users = [u for u in f1.read().split('\n') if u]
    zipped_list = list(itertools.izip(url_info, itertools.cycle(users)))    
    for item in zipped_list:        
        print item[0].replace('example', item[1])+"\n" 

输出:

URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/user2
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow

URL GOTO=https://www.url.com/user1
TAG POS=1 TYPE=BUTTON ATTR=TXT:Follow