[英]Copy N lines from File1 to File2, then delete copied lines in File1
[英]Generate Cartesian product of each word from file1 x file2
我搜索了很多站點和論壇,但無法正常運行。 我使用read(),readline()結合了各種解決方案。 我嘗試了while和for循環,但仍然無法弄清楚。 這是任務。 我有2個帶有txt
擴展名的文件。 所以file1是list1.txt
,文件2是list2.txt
list1.txt有
dog
flower
person
list2.txt有
123
456
接下來是我想要的。 新文檔list3.txt具有:
dog123
dog456
flower123
flower456
person123
person456
但是我無法使用itertool,因為我無法合並2個文件。 那是禁止的。 Any1可以幫助您找到解決方案或提供一些建議。
看一下輸入和輸出文檔:
with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3:
for i, l in enumerate(l1):
x = l1.readline()
for j, k in enumerate(l2):
l3.write('%s%s' % (x, l2.readline()))
這有效:
with open('list1.txt', 'r') as l1, open('list2.txt', 'r') as l2, open('list3.txt', 'w') as l3:
for left_part in l1:
for right_part in l2:
l3.write('%s%s\n' % (left_part.replace("\n",""), right_part.replace("\n","")))
l2.seek(0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.