Python file reads the pit of the ReadLines () method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.