w = open("input1.txt", "r")
f = open("input2.txt", "r")
for line1 in w:
words1 = line1.split()
for line2 in f:
words2 = line2.split()
print (words1[0]+" "+words1[1]+" "+words1[2]+" "+words1[3]+" "+words1[4]+" "+words1[5]+";"+words2[0])
f.close()
w.close()
我在每个文本文件中都有一个列表:input1.txt 和 input2.txt
input1.txt:1 2 3
input2.txt:a b c
我正在尝试加入每个元素与另一个元素配对的列表。 所以,输出应该是:
1a
1b
1c
2a
2b
2c
3a
3b
3c
使用上面的代码,我只能做到:
1a
1b
1c
结束。
我怎样才能让它选择下一行并重新做同样的事情?
请您参考如下方法:
在我看来你真正需要的是这个:
w = open("input1.txt", "r").read()
f = open("input2.txt", "r").read()
for number in w.split():
for letter in f.split():
print number, letter
f.close()
w.close()
只需拆分结果并正常迭代两者即可。您将获得配对的数字和字母,而无需您已经创建的所有额外(?)代码。
编辑以反射(reflect)来自 OP 的新信息
要完成您要求的操作,请像这样使用 readlines():
f = open("input2.txt", "r").read().split()
w = open("input1.txt", "r").readlines()
for timestamp in w:
for letter in f:
print timestamp.rstrip(), letter
rstrip 方法将处理使用 readlines() 自动传入的 newline 字符。
