为text1中的所有元素打印相同的ID,然后为text2修改ID和打印。python

2024-09-25 12:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文本文件text1.txt和text2.txt

text1.txt包含:

sam
mat
tom

text2.txt包含:

robbie
peter
steve

我希望输出类似:-

sam1
mat1
tom1
robbie2
peter2
steve2

因此,对于text1.txt元素,我希望为所有元素打印相同的ID,然后将ID增加1,并将其对应于text2.txt中的元素/名称进行打印,如上所示

有什么帮助吗? 谢谢


Tags: txtid元素sampetersteve文本文件tom
2条回答

试试这个:

files = ['text1.txt', 'text2.txt']

for (id, file) in enumerate(files, start=1):
    with open(file, 'r') as f:
        for line in f.xreadlines():
            print line.strip() + str(id)
>>> for i, f in enumerate([open('text1.txt'), open('text2.txt')], start=1):
...     for line in f:
...             print '%s%s' % (line.strip(), i)
...     f.close()
... 
sam1
mat1
tom1
robbie2
peter2
steve2

相关问题 更多 >