First, demand:
There are two files similar to the following which need to be compared and processed.
1.txt1231
2.txtABCD
Second, the question:
The first thing to think about is when you open it, two times for the loop.
#错误写法f1=open(r"D:\pytest\1.txt",‘r‘)f2=open(r"D:\pytest\2.txt",‘r‘)for x in f1.readlines(): for y in f2.readlines(): print(x.strip()+y.strip())
The output results are only
1A1B1C1D
Obviously the first layer has not been looped through.
So the test, look for Ah, finally understand. ReadLines () is a one-time job, read into memory and the iteration is complete without
#输出测试f1=open(r"D:\pytest\1.txt",‘r‘)f2=open(r"D:\pytest\2.txt",‘r‘)x1=f1.readlines()for x in x1: x2=f2.readlines() print(‘x2 is : {}‘.format(x2)) for y in x2: print("X : {}".format(x.strip())) print("y:{}".format(y.strip()))
Output
x2 is : [‘A\n‘, ‘B\n‘, ‘C\n‘, ‘D‘] #明显只请求一次X : 1y:AX : 1y:BX : 1y:CX : 1y:Dx2 is : [] #之后不再重新请求,已成空值,外层停止循环x2 is : []x2 is : []
Third, the settlement
You can assign a variable to it in the outer layer to store it . Modify the code as follows, finally 2 layer loop normal output.
#可用写法1f1=open(r"D:\pytest\1.txt",‘r‘)f2=open(r"D:\pytest\2.txt",‘r‘)X1=f1.readlines()X2=f2.readlines()for x in X1: for y in X2: print(x.strip()+y.strip())
In the process of finding a method, it is found that the with open is clearer than directly with open and does not use explicit close (), so the code is modified
#可用写法2with open(r"D:\pytest\1.txt",‘r‘) as f1,open(r"D:\pytest\2.txt",‘r‘) as f2: f11=f1.readlines() f22=f2.readlines() for x in f11: for y in f22: print(x.strip()+y.strip())
Test environment is under Windows python3.6
Python file reads the pit of the ReadLines () method