Why does Python CSV module make the CSV file read-only when I try to open it after running program?
Question: I'm using a program (follows) to see the similarities in certain columns
between two CSV files, then create a third when data matches certain
specifications (two columns are the same but the third is not) so that I can
update an e-mail list.

When I try to open the results.csv file after running the program however,
Windows Excel will only open the program in read-only mode.

Any thoughts?

Here's my code:

    
    
    import csv
    
    sample_data = open("sample.csv", "r")
    lib_data = open("library.csv", "r")
    csv1 = csv.reader(sample_data)
    csv2 = csv.reader(lib_data)
    
    results = open("results.csv", "w")
    res_csv = csv.writer(results)
    
    limit = 1071
    limit2 = 1001
    
    x = 0
    y = 0
    
    while (y != limit):
        row1 = csv1.__next__()
        while (x != limit2):
            row2 = csv2.__next__()
            if (row1[0] == row2[3] and row1[1] == row2[2] and row1[2] != row2[5]):
                print ("SAMPLE:")
                print (row1[0], ", ", row1[1], ", ", row1[2])
                print ("LIBRARY:")
                print (row2[3], ", ", row2[2], ", ", row2[5])
                print("\n")
                res_csv.writerow(row1)
            x = x+1
        y = y+1
        x = 0
        lib_data.seek(0)
    


Answer: Use `with` to ensure files will be closed properly:

    
    
    with open("sample.csv", "r") as sample_data:
        with open("library.csv", "r") as lib_data:
            with open("results.csv", "w") as results:
                # other code
    

You can even put several variables into one `with` if you're using Python >=
2.7.

