[英]Python Search text file & replace
我想從textfile1.txt中獲取一個單詞列表,並將textfile2.txt上的單詞“example”替換為第一行,第二行等文本的內容。我將如何做到這一點?
文本文件textfile1.txt
user1
user2
user3
user4
user5
文本文件textfile2.txt
url/example
url/example
url/example
url/example
url/example
到目前為止我有什么
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput("textfile2.txt", inplace=True ) as file:
for line in file:
print(line.replace("example", "user1"), end='')
我的目標:
url/user1
url/user2
url/user3
這應該做到這一點。 通常,當您想要並行遍歷2個或更多個iterables(列表,文件等)時,您可以使用zip
。
with open('textfile1.txt') as f1, open('textfile2.txt') as f2:
for l, r in zip(f1, f2):
print(r[:r.find('/')+1] + l)
我會打開第一個文件並將每行讀入一個數組: ['user1', 'user2', ...]
然后,當您閱讀第二個文件時,請跟蹤您的行號。 根據行號索引到數組中,並使用該字符串作為替換字符串。
或者使用zip()答案,這也沒關系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.